Search code examples
pythonstatic-methodsclass-methodfirst-class

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.


Solution

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