Python 官方文档:入门教程 => 点击学习
class Computer: """电脑""" # __slots__ = ('_name', 'mem', 'cpu') def __init__(self, name, mem, cpu): s
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
--结束END--
本文标题: python中,类属性为只读属性
本文链接: https://www.lsjlt.com/news/188789.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0