python 为 class 添加新的属性和方法

通过继承:

>>> class Point(namedtuple('Point', ['x', 'y'])):
...     __slots__ = ()
...     @property
...     def hypot(self):
...         return (self.x ** 2 + self.y ** 2) ** 0.5
...     def __str__(self):
...         return 'Point: x=%6.3f  y=%6.3f  hypot=%6.3f' % (self.x, self.y, self.hypot)

>>> for p in Point(3, 4), Point(14, 5/7):
...     print(p)
Point: x= 3.000  y= 4.000  hypot= 5.000
Point: x=14.000  y= 0.714  hypot=14.018

__slots__: 元组、列表、可迭代对象

当一个类需要创建大量实例时,通过_slots_可以声明实例所需要的属性。

slots主要用于优化内存和属性的访问速度,也可以用于限制子类中的属性,但这不是主要用途。

使用__slots__要注意,__slots__定义的属性仅对当前类起作用,对继承的子类是不起作用的

通过MethodType:

class Student:
    pass


s = Student()

单独给某个实例动态添加方法:

def func(self, x):
        print(x)


from types import MethodType
s.func = MethodType(func, s, Student)

给类动态绑定方法:

def set_score(self, score):
    self.score = score


Student.set_score = MethodType(set_score, None, Student)

猜你喜欢

转载自www.cnblogs.com/BeautifulWorld/p/11647266.html