繁体   English   中英

将函数存储为类变量但不带自参数调用

[英]Store function as class variable but call without self argument

我有一系列子类,每个子类都有自己的访问数据的功能。 有时,它可能更复杂,但默认情况下它会调用该方法(请参见下面的示例)。 当我尝试简单地调用定义的函数并将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")

暂无
暂无

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

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