繁体   English   中英

如何在 Python 中更改类实例的方法?

[英]How to Change a Class Instance's Method in Python?

我想创建一个python库,这个库的部分功能涉及创建一个带有一些用户定义变量的类实例。 如何让用户在所述实例的方法中为类实例编写自己的条件? 例如,假设我有以下类的实例:

class Test:
    def __init__(self, some_value):
        self.some_value = some_value
    def func(self):
        pass

instance = Test(4)

如何让用户更改instance.func()的功能(如何让用户访问对象的变量?

您可以将用户函数的引用传递给init例如:

class Test:
    def __init__(self, user_function):
        self._function = user_function
    def func(self):
        return self._function()

def ufunc_1():
    return 'Hello world!'

def ufunc_2():
    return 'Goodbye cruel world'


t_1 = Test(ufunc_1)
t_2 = Test(ufunc_2)

print(t_1.func())
print(t_2.func())

这样,对用户函数的引用存储在实例变量中。

输出:

Hello world!
Goodbye cruel world

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM