Reputation: 5343
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.
an_attr
must be a class attributeAnotherClassB
hello()
remained a classmethodAny ideas?
Upvotes: 0
Views: 83
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
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
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