首页 > 解决方案 > 动态分配类函数

问题描述

说我有课,TestClass. 我想要做的是有一个函数,我可以将 TestClass 的实例传递给它,它将test_function对象的属性设置为一个新函数,该函数将 self 作为第一个参数。我该怎么做?例子:

class TestClass:
    def __init__(self):
        self.t = "t" #irrelevant

object = TestClass()

def assign_function(object):
    object.test_function = #????????

assign_function(object)

object.test_function() #I want this line to be able to run and for test_function to be able to access the attributes of object

我已经尝试了一些选项,但似乎找不到任何有效的方法。对于我的大多数解决方案,该函数需要一个额外的参数,所以对于像这样的函数

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

我仍然需要将某些东西作为 self 传递,而不是像类函数那样自动完成

标签: python

解决方案


推荐阅读