python - 将函数存储为类变量,但调用时不带 self 参数

标签 python

我有一系列子类,每个子类都有自己的访问数据的功能。有时,它可能更复杂,但默认情况下它会调用该方法(参见下面的示例)。当我尝试简单地调用定义的函数并通过 self 时出现问题作为论据。没有为此定义数据访问函数签名,而是以其他方式使用,因此将 self 作为参数添加是没有意义的。我怎样才能通过正确的实现来完成这个设计?

# data.py

def get_class_a_records(connection, date):
    pass


def get_class_b_records(connection, date):
    pass


class Parent:
    def get_records(self, connection, **kwargs):
        self.data_method(connection=connection, **kwargs)


class A(Parent):
    data_method = get_class_a_records


class B(Parent):
    data_method = get_class_b_records


class C(Parent):
    def get_records(self, connection, **kwargs):
        # logic for custom code/post-processing
        pass
现在,如果我们实例化这些类之一,我们会遇到一个问题:
a = A()
a.get_records(connection=None, date='test')
TypeError: get_class_a_records() got multiple values for argument 'connection'
这是因为调用 self.data_method实际通过self作为参数,我们看到 get_class_a_records显然没有self作为论据。

最佳答案

你可以任意调用实例方法的第一个参数,但是当调用该方法时,python 总是会在该位置插入对实例对象的引用。通过分配 get_class_a_records类变量的函数,恭喜,你已经把它变成了一个实例方法。从技术上讲,当你调用它时,python 会使其成为一个实例方法。
类和静态方法的规则是不同的。对于一个类,传递实例的类对象。对于静态方法,没有添加任何内容。那就是你想要的那个。只需将函数转换为 staticmethod它会起作用。

def get_class_a_records(connection, date):
    print("class a records", connection)


def get_class_b_records(connection, date):
    pass


class Parent:
    def get_records(self, connection, **kwargs):
        self.data_method(connection=connection, **kwargs)


class A(Parent):
    data_method = staticmethod(get_class_a_records)


class B(Parent):
    data_method = staticmethod(get_class_b_records)


class C(Parent):
    def get_records(self, connection, **kwargs):
        # logic for custom code/post-processing
        pass

A().data_method("connection", "date")

关于python - 将函数存储为类变量,但调用时不带 self 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63909941/

相关文章:

python - 如何使用列表有条件地从 Pandas DataFrame 中删除重复项

python utf-8编码抛出UnicodeDecodeError尽管 "errors = '替换'“

Python:列表理解奇怪的行为

python - TensorFlow 整个数据集存储在图中

python - 在 Django 1.11 和 django _rest 框架中的嵌套序列化器上实现更新方法

Python - Oauth2 的 SSL 问题

python - PyAudio 复制设备

python - 如何从html页面中提取文本?

python - 带有 LIMIT 的自定义 get_queryset for django 管理面板

python - Django:使用 Javascript 解析我的模板中的 JSON