class Person:
# 类属性,通过类名访问,属于整个类,而不是某个对象
# nation = '中国'
# 限制可以使用的属性,提高访问的效率
# 也可以提高访问速度,减少内存使用
__slots__ = ('name', 'age', 'nation')
def __init__(self, name):
self.name = name
self.nation = 'china'
p1 = Person('小明')
p2 = Person('小红')
print(p1.name, p2.name)
print(Person.nation)
# p1.nation = 'china'
print(p1.nation)
print(p2.nation)
# print(Person.nation)
p1.age = 20
# p1.height = 180
# 特殊的类属性
# 表示类名的字符串
print(Person.__name__)
# 表示父类构成的元组
print(Person.__bases__)
# 存储类的相关信息
print(Person.__dict__)
# 限制可以使用的属性
print(Person.__slots__)
python 类的属性
最新推荐文章于 2024-05-16 18:12:08 发布