python - 动态分配类函数
问题描述
说我有课,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 传递,而不是像类函数那样自动完成
解决方案
推荐阅读
- flutter - 无法将JPG图像转换为PNG格式
- python - TemplateDoesNotExist 在,源不存在
- python - 在 python3 dict 中包含 unicode 字符
- ios - 尝试将 Json 数据解析到模型类中,使用可编码时出现错误
- python - 如何使用包和网格布局将可滚动框架中的所有元素水平居中
- selected - 垫子自动完成选定的值
- microsoft-teams - 具有嵌入式 Web 视图的 Teams 消息传递扩展 - Web 应用程序的结构
- css - 防止 Chrome 浏览器将位置属性转换为插入
- python - 为什么我的数据框没有附加到迭代中?
- javascript - 如何防止Angular自动导航到页面中间