开发者

Python - classmethod in base class accessible via child class, without passing in class

I'm trying to define some methods in a base class that can then be used as class/static methods on a child class, like so:

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)

How can I define find in Common such that it is usable in Foo without having to redefine it in Foo or do a passthrough in Foo to the method in Common? I also don't want to have to call Foo.find(Foo, 3). I'm using Python 2.6.

Edit: derp, looks like开发者_运维技巧 I had another find declared in Common that I hadn't noticed, and it was causing the TypeError. I would delete this question, but Nix mentioned code smells, so now I ask for suggestions on how to avoid defining find across all my model classes in a non-smelly way.


This doesn't quite answer your question but it might be of use to you.

An SQLAlchemy session instance has query_property() which returns a class property that produces a query against the class. So you could implement something similar to your find() method thus:

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

class Foo(Base):
    pass

Foo.query.get(id)


The problem was I had another find method defined in Common, so that was the one getting used and causing the TypeError.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜