property :
class Goods(object): def __init__(self): # 原价 self.original_price = 100 # 折扣 self.discount = 0.8 @property def price(self): new_price = self.original_price * self.discount return new_price @price.setter def price(self, value): self.original_price = value @price.deleter def price(self): del self.original_price obj = Goods() print(obj.price) obj.price = 200 print(obj.price) del obj.price
类成员修饰符:
class C: __name = "私有静态字段" def func(self): print(C.__name) # 类内部可以访问 class D(C): def show(self): print(C.__name) # 派生类中不可以访问 print(C.__name) # 类不可以访问 obj = C()
obj.func() obj_son = D() obj_son.show()
如果想要强制访问私有字段,可以通过 【对象._类名__私有字段明 】访问(如:obj._C__foo),不建议强制访问私有成员。
class C: def __init__(self): self.__foo = "私有字段" def func(self): print self.foo # 类内部访问 class D(C): def show(self): print self.foo # 派生类中访问 obj = C() obj.__foo # 通过对象访问 ==> 错误 obj.func() # 类内部访问 ==> 正确 obj_son = D(); obj_son.show() # 派生类中访问 ==> 错误
原文:https://www.cnblogs.com/yanxiaoge/p/10497744.html