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