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)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM