python-7面向对象高级编程

1-给类动态增加方法

class Student(object):
    pass
    
def set_score(self, score):
    self.score = score

Student.set_score = set_score #动态给类增加方法
s = Student()
s.set_score('dasheng')
print(s.score) #dasheng 

2-使用 __slots__ 限制实例属性

class Student(object):
    __slots__ = ('name', 'age') # 用tuple定义允许绑定的属性名称
    
#使用__slots__要注意,__slots__定义的属性仅对当前类实例起作用,对继承的子类是不起作用的: 
#除非在子类中也定义__slots__,这样,子类实例允许定义的属性就是自身的__slots__加上父类的__slots__。

3- @property使用 (方便使用,属于装饰器)

class Student(object):

    @property #可读
    def birth(self):
        return self._birth

    @birth.setter #可写
    def birth(self, value):
        self._birth = value

    @property
    def age(self): #可读,由于没有age.setter方法,表示只读
        return 2015 - self._birth

s = Student()
s.birth = 2011 #设置值
print(s.birth)  #获取值

4-多重继承, 由于Python允许使用多重继承,因此,MixIn就是一种常见的设计。

class MyTCPServer(TCPServer, ForkingMixIn):
    pass

5-定制类

__str__(self) 或 __repr__() #让打印对象更好看

__iter__(self) #用于for ... in循环
def __iter__(self):
        return self # 实例本身就是迭代对象,故返回自己

__getitem__ #取下标 Fib()[5]
    def __getitem__(self, n):
        a, b = 1, 1
        for x in range(n):
            a, b = b, a + b
        return a

__getattr__() #当调用不存在的属性时,会试图调用__getattr__(self, 'score')来尝试获得属性
     def __getattr__(self, attr):
        if attr=='age':
            return lambda: 25    

  
__call__ #直接对实例进行调用
#通过callable()函数,我们就可以判断一个对象是否是“可调用”对象

介绍的是最常用的几个定制方法,还有很多可定制的方法,请参考Python的官方文档

猜你喜欢

转载自www.cnblogs.com/qinzb/p/9035350.html