python add new properties and methods for the class

By inheritance:

>>> 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__: tuples, lists, iterables

When a class you need to create a large number of instances, you can declare instance attributes required by _slots_.

slots are mainly used to optimize memory access speed and properties, can also be used to limit the subclass properties, but this is not the main purpose.

Use __slots__should be noted that __slots__the definition of property is valid only current class, sub-class inheritance does not work

 

By MethodType:

class Student:
    pass


s = Student()

Examples of a method for dynamically added separately:

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


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

Dynamic binding method to the class:

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


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

 

Guess you like

Origin www.cnblogs.com/BeautifulWorld/p/11647266.html