标签:set ice ini discount new 字典 重写 __init__ 属性
如果希望创建某一批类全部具有某种特征,则可通过metaclass来实现。使用metaclass可以在创建类时动态修改类定义。
class ItemMetaClass(type): # cls 代表被动态修改的类 # name 代表被动态修改的类名 # bases 代表被动态修改的类的所有父类 # attr 代表被动态修改的类的所有属性、方法组成的字典 def __new__(cls, name, bases, attrs): attrs[‘cal_price‘] = lambda self: self.price * self.discount return type.__new__(cls, name, bases, attrs) class Book(metaclass=ItemMetaClass): __slots__ = [‘name‘, ‘price‘, ‘_discount‘] def __init__(self, name, price): self.name = name self.price = price @property def discount(self): return self._discount @discount.setter def discount(self, discount): self._discount = discount class CellPhone(metaclass=ItemMetaClass): __slots__ = [‘price‘, ‘_discount‘] def __init__(self, price): self.price = price @property def discount(self): return self._discount @discount.setter def discount(self, discount): self._discount = discount b = Book(‘九年级数学上‘, 89) b.discount = 0.76 print(b.cal_price()) cp = CellPhone(2399) cp.discount = 0.85 print(cp.cal_price())
谢谢!
标签:set ice ini discount new 字典 重写 __init__ 属性
原文地址:https://www.cnblogs.com/zhzhang/p/11899657.html