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
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有