Python內(nèi)置的@property裝飾器可以把類的方法偽裝成屬性調(diào)用的方式。也就是本來是Foo.func()的調(diào)用方法,變成Foo.func的方式。
一旦給函數(shù)加上一個裝飾器@property,調(diào)用函數(shù)的時候不用加括號就可以直接調(diào)用函數(shù)了。
# 創(chuàng)建一個學(xué)生類
class Student:
# 定義學(xué)生屬性,初始化方法
# name和score屬于實例變量, 其中score屬于私有變量
def __init__(self, name, score):
self.name = name
self.__score = score
# 利用property裝飾器把函數(shù)偽裝成屬性
@property
def score(self):
print("Name: {}. Score: {}".format(self.name, self.__score))
# 實例化,創(chuàng)建對象
student1 = Student("John", 100)
student1.score # 打印 Name: John. Score: 100