python

    xiaoxiao2021-03-26  29

    如下面的一个类:

    class OldResistor(object): def __init__(self,ohms): self.ohms = ohms def get_ohms(self): return self.ohms def set_ohms(self, ohms): self._ohms = ohms a = OldResistor(50e3) print ('no set %5r'% a.get_ohms()) a.set_ohms(10e3) print ('with set %5r'% a.get_ohms())

    结果:

    no set 50000.0 with set 10000.0

    init方法在实例被创建时初始化,它可以把各种属性绑定到self,然后self指向被创建的实例本身(在这里是a)。然后,对象调用setter可以改变属性。上面代码还可以简化成: setter还可以配合@property使用,效果和之前一样:

    转载请注明原文地址: https://ju.6miu.com/read-662641.html

    最新回复(0)