[Python3] 类的高级用法:给实例和类动态绑定属性和方法

Python是动态语言,它可以在写好了一个类之后再给类动态地添加属性和方法
对于类生成出的实例同样可以这样做

要实现这一功能需要借助一个方法:MethodType
用法:

<类(或者实例)>.<为要添加的方法或属性起的名字> = MethodType(<要添加的方法或属性>, 类(或者实例))

举例:

可以先这样导入这个方法 from types import MethodType
假设我们定义一个 Student 类:

class Student(object):
    pass

    1
    2

现在里面什么也不写,我们在外面给它动态增加方法
考虑这样一个函数:

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

    1
    2

只需写入这样一行代码即可把set_score() 方法添加为 Student 类的 .set_score() 方法:

Student.set_score = MethodType(set_score, Student)

    1

之后就可以这样使用这个方法了:

Student.set_score(99)

    1

绑定属性以及对类实例绑定的做法类似

下面是一个DEMO:

# 类的高级用法1

from types import MethodType


class Student(object):
    pass


def main():
    s = Student()
    s.name = 'Bob'
    print(s.name)

    def set_age(self, age: int):    # 给实例定义的方法
        self.age = age

    s.set_age = MethodType(set_age, s)  # 将方法与一个实例绑定, 这样实例s就有了set_age()方法

    s.set_age(5)                        # 这样一来实例s有了一个属性: s = 5
    print(s.age)

    # 当然也可以给类绑定方法
    def set_score(self, score: int):
        self.score = score

    Student.set_score = MethodType(set_score, Student)
    Student.set_score(99)
    print(Student.score)
    # 这样Student类就有了set_score()方法和score属性,该类所有实例都可用,如下:

    s.set_score(80)
    print(s.score)  # 会输出80而不是99


if __name__ == '__main__':
    main()

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37

运行结果:

Bob
5
99
80
---------------------
作者:Bob Xiao
来源:CSDN
原文:https://blog.csdn.net/qq_17592003/article/details/82704968
版权声明:本文为博主原创文章,转载请附上博文链接!

posted @ 2019-07-20 08:53  天涯海角路  阅读(301)  评论(0)    收藏  举报