首页 > 解决方案 > 如何将可调用对象传递给类,以便它可以访问 Python 中的实例属性?

问题描述

假设我有这个类:

class ClassA:
    def __init__(self, callable):
        self.name = "Hey!"
        self.callable = callable

    def call(self):
        self.callable()

我想传入callable一个可以访问的函数name

def function_a():
    print(f"{self.name}")

所以这

a = ClassA(function_a)
a.call()

产生这个:

Hey!

我该怎么办?元分类?班级装修?还是我应该彻底检查我的架构,这样我就不需要做这样的事情了?

使用更清晰的示例进行编辑

前一个示例似乎我只是想访问该属性,事实并非如此。在更复杂的演示中,考虑一下:

class ClassA:
    def __init__(self, selection):
        self.numbers = [randint(1, 100) for _ in range(10)]
        self.selection = selection

    def select(self):
        return self.selection(self.numbers)

然后假设我希望呼叫者能够提供不同的策略来选择这些号码,比如

a = ClassA(selection_strategy)
a.select()

在该架构中,selection_strategy是在类之外定义的可调用对象,它需要以某种方式访问​​该对象的属性。

Aaaa 就在我写这篇文章的时候,我意识到我想要的其实很简单,我只需selection_strategy 要从类中接受我想要的参数并在 select. 对不起,我已经工作了几个小时,这完全被我忽略了。

谢谢!

标签: python

解决方案


The callable can't officially be a method because methods must be defined on the class object itself. But does it really have to be a method? You could just define the callable as a regular function taking a single parameter that just happens to be an instance object's self reference. Namespace resolution is different - you can't use class level variables - but if that's not a problem, this will work:

class ClassA:
    def __init__(self, callable):
        self.name = "Hey!"
        self.callable = callable

    def call(self):
        self.callable(self)

def function_a(self):
    print(f"{self.name}")

a = ClassA(function_a)
a.call()

推荐阅读