class Parrot: def __init__(self): self._voltage = 10000 @property def voltage(self): '''Get the current voltage''' return self._voltage @voltage.setter def s_vol(self, value): '''set the current vol''' self._voltage = value @voltage.deleter def d_vol(self): '''del the current vol''' del self._voltage p = Parrot() print(p.voltage) p.s_vol = 20000 print(p.s_vol) p.s_vol = 30000 print(p.s_vol)
class Student(object): @property def score(self): return self._score @score.setter def score1(self, value): if not isinstance(value, int): raise ValueError('score must be an integer!') if value < 0 or value > 100: raise ValueError('score must between 0~100') self._score = value @score.deleter def score2(self): del self._score s = Student() s.score1 = 60 print(s.score) #返回60 s.score1 = 90 print(s.score) #返回90
class A(object): #属性默认为类属性(可以直接被类调用) num = 100 #实例化方法(必须实例化类之后才能被调用,即A().func()) def func(self): print('func') print(self) #返回<__main__.A object at 0x7fb9c8111a30>,self表示实例化类后的内存地址id @classmethod #类方法,不需要实例化就可以被类本身调用,即A.func1() def func1(cls): #cls表示没有被实例化的类本身 print('func1') print(cls) print(cls.num) cls().func() #不传递默认self参数的方法(该方法也是可以直接被类调用,但是这样做不标准) def func2(): print('func2') print(A.num) #属性是可以直接用类本身调用 A.func1() ''' 返回结果: func1 <class '__main__.A'> 100 func <__main__.A object at 0x7f84c81b9a30> ''' A.func2() #返回结果: # func2 # 100 A().func() #返回结果: # func #<__main__.A object at 0x7f9578179a30>
class C(object): @staticmethod def f(): print('这是一个静态方法') C.f() #返回: 这是一个静态方法 C().f() #返回: 这是一个静态方法 class C1(object): @staticmethod class C2(object): def __init__(self, val = 1): self.val = val def shout(self): print('这是一个静态方法参数:%s '% self.val) C1.C2().shout() #返回结果: 这是一个静态方法参数:1