Python - 基类中的classmethod如何在子类中访问,无需传递类

0 投票
2 回答
1100 浏览
提问于 2025-04-16 21:07

我想在一个基类里定义一些方法,这样这些方法就可以在子类中作为类方法或静态方法使用,像这样:

class Common():
    @classmethod
    def find(cls, id): # When Foo.find is called, cls needs to be Foo
        rows = Session.query(cls)
        rows = rows.filter(cls.id == id)
        return rows.first()

class Foo(Common):
    pass

>> Foo.find(3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: find() takes exactly 2 arguments (1 given)

我该如何在 Common 里定义 find,使得在 Foo 中可以直接使用,而不需要在 Foo 里重新定义它,或者通过 Foo 传递到 Common 的方法?我也不想调用 Foo.find(Foo, 3)。我使用的是 Python 2.6。

编辑:哎呀,看起来我在 Common 里有另一个 find 的定义,我之前没注意到,这导致了 TypeError。我本来想删掉这个问题,但 Nix 提到了代码气味,所以我现在想请教一下,如何避免在我所有的模型类中以不好的方式定义 find

2 个回答

0

这虽然没有完全回答你的问题,但可能对你有帮助。

一个SQLAlchemy的会话实例有一个叫做 query_property() 的功能,它可以返回一个类属性,用来对这个类进行查询。所以你可以用类似于你的 find() 方法的方式来实现:

Base = declarative_base()
Base.query = db_session.query_property()

class Foo(Base):
    pass

Foo.query.get(id)
0

问题是我在Common里定义了另一个find方法,所以程序用的是那个方法,导致出现了TypeError错误。

撰写回答