<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                合規國際互聯網加速 OSASE為企業客戶提供高速穩定SD-WAN國際加速解決方案。 廣告
                {% raw %} # Python 魔術方法 > 原文: [http://zetcode.com/python/magicmethods/](http://zetcode.com/python/magicmethods/) Python 魔術方法教程描述了什么是 Python 魔術方法,并說明了如何使用它們。 在本教程中,我們介紹了一些常見的魔術方法。 ## Python 魔術方法 Python 魔術方法是為我們的自定義類添加功能的特殊方法。 它們被雙下劃線包圍(例如`__add __()`)。 Python 中有許多魔術方法。 它們中的大多數用于非常特殊的情況。 我們將提到一些更流行的方法。 ## `__add__`方法 `__add__()`方法用于實現加法運算。 在 Python 中,數字不是原始字面值,而是對象。 `num + 4`表達式等效于`num.__add__(4)`。 `add_dict.py` ```py #!/usr/bin/env python class MyDict(dict): def __add__(self, other): self.update(other) return MyDict(self) a = MyDict({'de': 'Germany'}) b = MyDict({'sk': 'Slovakia'}) print(a + b) ``` 在示例中,我們有一個自定義字典,該字典使用`__add__()`實現加法運算。 ```py class MyDict(dict): def __add__(self, other): self.update(other) return MyDict(self) ``` 自定義字典繼承自內置`dict`。 `__add__()`方法與`update()`方法添加兩個字典,并返回新創建的字典。 ```py a = MyDict({'de': 'Germany'}) b = MyDict({'sk': 'Slovakia'}) ``` 我們創建兩個簡單的字典。 ```py print(a + b) ``` 我們添加兩個字典。 ```py $ ./add_dict.py {'de': 'Germany', 'sk': 'Slovakia'} ``` 這是輸出。 ## `__init__`和`__str__`方法 `__init__()`方法用于初始化對象。 此方法用于實現對象的構造器。 `__str__()`提供了對象可讀的輸出。 `init_str.py` ```py #!/usr/bin/env python class Person: def __init__(self, name, occupation): self.name = name self.occupation = occupation def __str__(self): return f'{self.name} is a {self.occupation}' p = Person('John Doe', 'gardener') print(p) ``` 在示例中,我們有一個`Person`類,具有兩個屬性:`name`和`occupation`。 ```py def __init__(self, name, occupation): self.name = name self.occupation = occupation ``` 在`__init__()`方法中,我們將實例變量設置為傳遞給構造器的值。 ```py def __str__(self): return f'{self.name} is a {self.occupation}' ``` `__str__()`方法可以很好地輸出對象。 ```py $ ./init_str.py John Doe is a gardener ``` 這是輸出。 ## `__repr__`方法 `__repr__()`方法由內置函數`repr()`調用。 當它求值返回對象的表達式時,在 Python shell 上使用它。 `__str__()`用于提供對象的人類可讀版本,`__repr__()`用于提供對象的完整表示。 后者的輸出也更適合開發者。 如果缺少`__str__()`實現,則將`__repr__()`方法用作后備。 ```py def __repr__(self): return '<{0}.{1} object at {2}>'.format( self.__module__, type(self).__name__, hex(id(self))) ``` 對象的`__repr__()`方法的默認實現類似于上面的代碼。 `repr_ex.py` ```py #!/usr/bin/env python class Person: def __init__(self, name, occupation): self.name = name self.occupation = occupation def __str__(self): return f'{self.name} is a {self.occupation}' def __repr__(self): return f'Person{{name: {self.name}, occupation: {self.occupation}}}' p = Person('John Doe', 'gardener') print(p) print(repr(p)) ``` 該示例實現了`__str__()`和`__repr__()`方法。 ```py $ ./repr_ex.py John Doe is a gardener Person{name: John Doe, occupation: gardener} ``` 這是輸出。 ## `__len__`和`__getitem__`方法 `__len__()`方法返回容器的長度。 當我們在對象上使用內置的`len()`方法時,將調用該方法。 `__getitem__()`方法定義項目訪問([])運算符。 `french_deck.py` ```py #!/usr/bin/env python import collections from random import choice Card = collections.namedtuple('Card', ['suit', 'rank']) class FrenchDeck: ranks = [str(i) for i in range(2, 11)] + list('JQKA') suits = ["heart", "clubs", "spades", "diamond"] def __init__(self): self.total = [Card(suit, rank) for suit in self.suits for rank in self.ranks] def __len__(self): return len(self.total) def __getitem__(self, index): return self.total[index] deck = FrenchDeck() print(deck[0]) print(len(deck)) print(choice(deck)) ``` 該方法用于實現法語卡片組。 ```py Card = collections.namedtuple('Card', ['suit', 'rank']) ``` 我們使用一個命名的元組來定義一個`Card`類。 `namedtuple`是用于創建元組類的工廠功能。 每張卡都有一套西裝和一個等級。 ```py def __len__(self): return len(self.total) ``` `__len__()`方法返回卡座(52)中的卡數。 ```py def __getitem__(self, index): return self.total[index] ``` `__getitem__()`實現索引操作。 ```py print(deck[0]) ``` 我們得到卡組的第一張牌。 這稱為`__getitem__()`。 ```py print(len(deck)) ``` 這將調用`__len__()`方法。 ```py $ ./french_deck.py Card(suit='heart', rank='2') 52 Card(suit='diamond', rank='A') ``` 這是輸出。 ## `__int__`和`__index__`方法 調用`__int__()`方法以實現內置的`int()`函數。 當在切片表達式中使用對象以及內置的`hex()`,`oct()`和`bin()`函數時,`__index__()`方法將類型轉換為`int`。 `char_ex.py` ```py #!/usr/bin/env python class Char: def __init__(self, val): self.val = val def __int__(self): return ord(self.val) def __index__(self): return ord(self.val) c1 = Char('a') print(int(c1)) print(hex(c1)) print(bin(c1)) print(oct(c1)) ``` 在示例中,我們創建一個自定義的`Char`類,該類實現了`int()`,`hex()`,`bin()`和`oct()`函數。 ```py ./char_ex.py 97 0x61 0b1100001 0o141 ``` 這是輸出。 ## `__eq __`,`__ lt__`和`__gt__`方法 `__eq__()`實現了`==`運算符。 `__lt__()`實現了`<`運算符,`__gt__()`實現了`>`運算符。 `pouch.py` ```py #!/usr/bin/env python import collections Coin = collections.namedtuple('coin', ['rank']) # a gold coin equals to two silver and six bronze coins class Pouch: def __init__(self): self.bag = [] def add(self, coin): self.bag.append(coin) def __eq__(self, other): val1, val2 = self.__evaluate(other) if val1 == val2: return True else: return False def __lt__(self, other): val1, val2 = self.__evaluate(other) if val1 < val2: return True else: return False def __gt__(self, other): val1, val2 = self.__evaluate(other) if val1 > val2: return True else: return False def __str__(self): return str(self.bag) def __evaluate(self, other): val1 = 0 val2 = 0 for coin in self.bag: if coin.rank == 'g': val1 += 6 if coin.rank == 's': val1 += 3 if coin.rank == 'b': val1 += 1 for coin in other.bag: if coin.rank == 'g': val2 += 6 if coin.rank == 's': val2 += 3 if coin.rank == 'b': val2 += 1 return val1, val2 pouch1 = Pouch() pouch1.add(Coin('g')) pouch1.add(Coin('g')) pouch1.add(Coin('s')) pouch2 = Pouch() pouch2.add(Coin('g')) pouch2.add(Coin('s')) pouch2.add(Coin('s')) pouch2.add(Coin('b')) pouch2.add(Coin('b')) pouch2.add(Coin('b')) print(pouch1) print(pouch2) if pouch1 == pouch2: print('Pouches have equal value') elif pouch1 > pouch2: print('Pouch 1 is more valueable than Pouch 2') else: print('Pouch 2 is more valueable than Pouch 1') ``` 我們有一個可以容納金,銀和青銅硬幣的小袋。 一枚金幣等于兩個銀幣和六個銅幣。 在示例中,我們使用 Python 魔術方法為`pouch`對象實現了三個比較運算符。 ```py def __eq__(self, other): val1, val2 = self.__evaluate(other) if val1 == val2: return True else: return False ``` 在`__eq__()`方法中,我們首先求值兩個小袋的值。 然后我們比較它們并返回布爾結果。 ```py def __evaluate(self, other): val1 = 0 val2 = 0 for coin in self.bag: if coin.rank == 'g': val1 += 6 if coin.rank == 's': val1 += 3 if coin.rank == 'b': val1 += 1 for coin in other.bag: if coin.rank == 'g': val2 += 6 if coin.rank == 's': val2 += 3 if coin.rank == 'b': val2 += 1 return val1, val2 ``` `__evaluate()`方法計算兩個袋的值。 它穿過小袋的硬幣,并根據硬幣的等級增加一個值。 ```py pouch1 = Pouch() pouch1.add(Coin('g')) pouch1.add(Coin('g')) pouch1.add(Coin('s')) ``` 我們創建第一個袋,并在其中添加三個硬幣。 ```py if pouch1 == pouch2: print('Pouches have equal value') elif pouch1 > pouch2: print('Pouch 1 is more valueable than Pouch 2') else: print('Pouch 2 is more valueable than Pouch 1') ``` 我們將小袋與比較運算符進行比較。 ## 2D 向量示例 在下面的示例中,我們介紹了幾種其他魔術方法,包括`__sub__()`,`__mul__()`和`__abs__()`。 `vector.py` ```py #!/usr/bin/env python import math class Vec2D: def __init__(self, x, y): self.x = x self.y = y def __add__(self, other): return Vec2D(self.x + other.x, self.y + other.y) def __sub__(self, other): return Vec2D(self.x - other.x, self.y - other.y) def __mul__(self, other): return self.x * other.x + self.y * other.y def __abs__(self): return math.sqrt(self.x ** 2 + self.y ** 2) def __eq__(self, other): return self.x == other.x and self.y == other.y def __str__(self): return f'({self.x}, {self.y})' def __ne__(self, other): return not self.__eq__(other) u = Vec2D(0, 1) v = Vec2D(2, 3) w = Vec2D(-1, 1) a = u + v print(a) print(a == w) a = u - v print(a) a = u * v print(a) print(abs(u)) print(u == v) print(u != v) ``` 在示例中,我們有一個`Vec2D`類。 我們可以比較,加,減和乘向量。 我們還可以計算向量的長度。 ```py $ ./vector.py (2, 4) False (-2, -2) 3 1.0 False True ``` 這是輸出。 在本教程中,我們使用了 Python 魔術方法。 您可能也對以下相關教程感興趣: [Python 字符串](/lang/python/strings/), [Python Jinja 教程](/python/jinja/)和 [Python 教程](/lang/python/),或列出[所有 Python 教程](/all/#python) 。 {% endraw %}
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看