Stephen Paulger
Stephen Paulger

Reputation: 5343

How can a python object's classmethods be referred to inside the class attributes?

I would like to do something along the lines of...

class MyClassA(object):
    an_attr = AnotherClassB(do_something=MyClassA.hello)

    @classmethod
    def hello(cls):
        return "Hello"

however it will tell me MyClassA is not defined when I try to run it.

Any ideas?

Upvotes: 0

Views: 83

Answers (3)

Thomas K
Thomas K

Reputation: 40370

You just have to get the order right, so it's defined before you use it:

class MyClassA(object):
    @classmethod
    def hello(cls):
        return "Hello"

    an_attr = AnotherClassB(do_something=hello)

Note that, because it's in the namespace when we're creating the class, we just refer to hello, not to MyClassA.hello.

EDIT: Sorry, this doesn't actually do what I thought it did. It creates the class without an error, but AnotherClassB only gets a reference to the unbound classmethod, which can't be called.

Upvotes: 3

Mew
Mew

Reputation: 1049

I'm not sure if this will work, but try it out?

class MyClassA(object):
    @classmethod
    def hello(cls):
        return "Hello"

  MyClassA.an_attr = AnotherClassB(do_something=MyClassA.hello)

Upvotes: 2

Sven Marnach
Sven Marnach

Reputation: 602115

While defining a class, the class does not exist yet. So you have to postpone the creation of an_attr until after the class definition:

class MyClassA(object):
    @classmethod
    def hello(cls):
        return "Hello"
MyClassA.an_attr = AnotherClassB(do_something=MyClassA.hello)

Upvotes: 3

Related Questions