1. 程式人生 > >面向對象的特殊方法

面向對象的特殊方法

python 對象特殊方法

特殊方法

__init__ :把各種屬性綁定到self

__slots__ : 限制實例的動態屬性,減少內存消耗,tuple類型

__str__: 對象的說明文字

__eq__:比較對象是否相等

classmethod 與staticmethod:classmethod 會把類本身作為第一個參數傳入。

class Computer:
    """電腦"""
    def __init__(self, name, mem, cpu):
        self._name = name 
        self.mem = mem
        self.cpu = cpu 

    def play(self, game=‘qq‘):
        print(‘play games:‘,game)
pc1 = Computer(‘coop‘,‘8G‘,‘8‘)  # 實例初始化,生成一個類的對象,具有類的屬性和方法
pc1
<__main__.Computer at 0x1ec1ec7f0f0>
pc1.play
<bound method Computer.play of <__main__.Computer object at 0x000001EC1EC7F0F0>>
pc1.play()
play games: qq
pc1.play(‘rongyao‘)
play games: rongyao
pc1.mem
‘8G‘
pc1._name
‘coop‘
pc1.cpu
‘8‘
#############
pc1.disk = ‘ssd‘
pc1.disk
‘ssd‘
class Computer:
    """電腦"""
    __slots__ = (‘_name‘, ‘mem‘, ‘cpu‘)
    def __init__(self, name, mem, cpu):
        self._name = name 
        self.mem = mem
        self.cpu = cpu

    def play(self, game=‘mosou‘):
        print(‘play game:‘,game)

    def __str__(self):
        return f‘{self._name}:{self.mem}-{self.cpu}‘
pc2 = Computer(‘admin‘, ‘8G‘, ‘8‘)
pc2.mem
‘8G‘
pc2.cpu
‘8‘
pc2._name
‘admin‘
pc2.disk = ‘disk‘
---------------------------------------------------------------------------

AttributeError                            Traceback (most recent call last)

<ipython-input-45-35b41d1e04d2> in <module>()
----> 1 pc2.disk = ‘disk‘

AttributeError: ‘Computer‘ object has no attribute ‘disk‘
print(pc2)
admin:8G-8
pc3 = Computer(‘admin‘,‘8G‘,8)
print(pc3)
admin:8G-8
pc2 == pc3
False
############
class Computer:
    """電腦"""
    __slots__ = (‘_name‘, ‘mem‘, ‘cpu‘)
    def __init__(self, name, mem, cpu):
        self._name = name 
        self.mem = mem
        self.cpu = cpu

    def play(self, game=‘mosou‘):
        print(‘play game:‘,game)

    def __str__(self):
        return f‘{self._name}:{self.mem}-{self.cpu}‘

    def __eq__(self, other):
        return self.cpu == other.cpu
pc2 = Computer(‘admin‘,‘8G‘,8)
pc3 = Computer(‘admin‘,‘8G‘,8)
pc2 == pc3
True
###########
class Computer:
    """電腦"""
    __slots__ = (‘_name‘, ‘mem‘, ‘cpu‘)
    def __init__(self, name, mem, cpu):
        self._name = name 
        self.mem = mem
        self.cpu = cpu

    def play(self, game=‘mosou‘):
        print(‘play game:‘,game)

    def __str__(self):
        return f‘{self._name}:{self.mem}-{self.cpu}‘

    def __eq__(self, other):
        return self.cpu == other.cpu

    @classmethod  # 通過新的方式構造實例,區別於默認的__init__,類似其他語言重載
    def new_pc(cls, info):  # 第一個參數為類本身
        "從字符串產生新的實例"
        name, mem, cpu = info.split(‘-‘)
        return cls(name, mem, cpu)

    @staticmethod  # 不需要生成類的實例,就可以使用的方法
    def calc(a, b, oper):  # 不用第一個參數
        "根據操作符號+-*/計算a和b的結果"
        if oper == ‘+‘:
            return a + b
# 使用classmethod建立新的對象
pc111 = Computer.new_pc(‘pc111-16G-8‘)
print(pc111)
pc111:16G-8
Computer.calc(4, 3, ‘+‘)
7
Computer.calc(2, 3, "-")

面向對象的特殊方法