‘‘‘
静态属性(property装饰器)
在给类的方法加入一个property装饰器后,实例再次调用类的方法无需加括号;便于封装,隐藏代码逻辑
‘‘‘
class School:
‘‘‘这是一个学校类‘‘‘
city = ‘江西‘
def __init__(self, name, principal, length, width, high):
self.name = name
self.principal = principal
self.length = length
self.width = width
self.high = high
def tell_info(self):
return ‘%s学校,占地面积为%s平米!‘ % (self.name, self.length*self.width)
s1 = School(‘三中‘, ‘张九明‘, 100, 100, 50)
print(s1.tell_info()) # 正常情况下调用类的方法
print(s1.city)
class School:
‘‘‘这是一个学校类‘‘‘
city = ‘广西‘
def __init__(self, name, principal, length, width, high):
self.name = name
self.principal = principal
self.length = length
self.width = width
self.high = high
@property
def tell_info(self):
return ‘%s学校,占地面积为%s平米!‘ % (self.name, self.length*self.width)
s2 = School(‘一中‘, ‘alex‘, 200, 200, 50)
print(s2.tell_info) # 在给类的方法加入一个property装饰器后,实例调用类的方法无需加括号;便于封装,隐藏代码逻辑
print(s2.city)
print(School.tell_info) # 类调用结果:<property object at 0x000001EA8FB7D040>,加上括号后会报错
原文:https://www.cnblogs.com/xuewei95/p/14651050.html