首页 > 其他 > 详细

静态属性

时间:2021-04-13 00:42:52      阅读:26      评论:0      收藏:0      [点我收藏+]
‘‘‘
静态属性(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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!