python中,類屬性為只讀屬性
阿新 • • 發佈:2018-07-13
can self all 屬性 error input 函數 clas rec
class Computer:
"""電腦"""
# __slots__ = (‘_name‘, ‘mem‘, ‘cpu‘)
def __init__(self, name, mem, cpu):
self._name = name
self.mem = mem
self.cpu = cpu
@property
def name(self): # 只讀, getter方法
return self._name
def play(self, game=‘qq遊戲‘):
print(‘play‘, game)
pc2 = Computer(‘admin‘, ‘8G‘, 8)
pc2.name # name()函數變成屬性了,
‘admin‘
pc2.name = 1 # 不能修改屬性
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-33-91d30e8bb3c6> in <module>() ----> 1 pc2.name = 1 AttributeError: can‘t set attribute
pc2.name() # 加了@property,不能調用name()函數了
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-34-e97dcaa201d9> in <module>() ----> 1 pc2.name() TypeError: ‘str‘ object is not callable
python中,類屬性為只讀屬性