欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

python动态修改类方法和实例方法

程序员文章站 2023-09-18 10:36:19
修改类方法直接将函数绑定到原有的方法上,函数的第一个参数依然是实例self,修改后的方法不仅会作用于新创建的实例,也会作用于修改前创建的实例。class Student: def __init__(self, name): self.name = name def self_introduce(self): print(f'I am {self.name}.')def new_self_introduce(self): print(f'My...

修改类方法

直接将函数绑定到原有的方法上,函数的第一个参数依然是实例self,修改后的方法不仅会作用于新创建的实例,也会作用于修改前创建的实例。

class Student:
    def __init__(self, name):
        self.name = name

    def self_introduce(self):
        print(f'I am {self.name}.')


def new_self_introduce(self):
    print(f'My name is {self.name}. Nice to meet you!')


a = Student('xiaoming')
a.self_introduce()

Student.self_introduce = new_self_introduce
a.self_introduce()

b = Student('xiaohong')
b.self_introduce()

输出:

I am xiaoming.
My name is xiaoming. Nice to meet you!
My name is xiaohong. Nice to meet you!

修改实例方法

若采用与上述相同的方式绑定

a.self_introduce = new_self_introduce
a.self_introduce()

则会出现错误

Traceback (most recent call last):
File “C:/Users/hmy/Documents/git/doc/spiders/hmyspiders/Script/test.py”, line 18, in <module>
a.self_introduce()
TypeError: new_self_introduce() missing 1 required positional argument: ‘self’

可见实例对象并没有作为参数传入新方法的self中,所以这种方法只能绑定不需要self参数的静态方法。这时可以用types中的MethodType函数来处理,参数为要绑定的新方法,实例,只作用于当前实例

from types import MethodType


class Student:
    def __init__(self, name):
        self.name = name

    def self_introduce(self):
        print(f'I am {self.name}.')


def new_self_introduce(self):
    print(f'My name is {self.name}. Nice to meet you!')


a = Student('xiaoming')
a.self_introduce()

a.self_introduce = MethodType(new_self_introduce, a)
a.self_introduce()

b = Student('xiaohong')
b.self_introduce()

输出:

I am xiaoming.
My name is xiaoming. Nice to meet you!
I am xiaohong.

本文地址:https://blog.csdn.net/jerrism/article/details/107357541