Krystian Cybulski
Krystian Cybulski

Reputation: 11108

Calling a static method inside of a Python class definition

I have a class definition which defines a static method. I have a field which I would like to initialize with the static method. My default thinking led me to this:

class SomeConcreteClass(object):
    some_data = SomeConcreteClass.create_default_data()
    @staticmethod
    def create_default_data():
        return 'Foo'

The problem is that when I run this, I get a NameError: name 'SomeConcreteClass' is not defined. It makes sense as the SomeConcreteClass is just being built. Does this mean I cannot use static init functions? Is there an alternate way which is recommended to handle such a situation?

Upvotes: 2

Views: 1038

Answers (3)

Duncan
Duncan

Reputation: 95622

The appropriate place for create_default_data would be outside the class entirely. Then your problems go away:

def create_default_data():
    return 'Foo'

class SomeConcreteClass(object):
    some_data = create_default_data()

If you really do want it as a static method inside the class that's alright too:

def _create_default_data():
    return 'Foo'

class SomeConcreteClass(object):
    some_data = _create_default_data()
    create_default_data = staticmethod(_create_default_data)

but static methods aren't often used in Python because there's no need to put a function inside a class unless it operates on the class in some way.

Upvotes: 3

ezod
ezod

Reputation: 7411

If some_data is exactly the output of create_default_data (and assuming the latter is deterministic in the context of your call) then why not just make some_data a @property?

class SomeConcreteClass(object):
    @property
    def some_data():
        return 'Foo'

Alternatively, but not equivalently, you could initialize some_data for each instance within __init__.

Upvotes: 1

Daniel Roseman
Daniel Roseman

Reputation: 599480

I don't think you want to do this. Don't forget that Python is not Java ™... attributes defined at class level are class attributes, not instance attributes. You almost certainly want the data to be instance-specific, so you should do this in the __init__ method. You can certainly call the classmethod from within that method, if you want to, or (better) just put the code in __init__.

Upvotes: 1

Related Questions