1
class Something(object):
    our_random = Something.random_thing

    @staticmethod
    def random_thing():
         return 4

Of course, this doesn't work, becauese Something doesn't exist when I attempt to call its method. Nor does this:

class Something(object):
    our_random = random_thing

    @staticmethod
    def random_thing():
         return 4

I've "solved" this by Just placing random_thing()'s definition above the class, but I find this messy.

1
  • Did you mean to call random_thing? Commented May 31, 2013 at 21:09

2 Answers 2

3

Call it in the .__init__() initializer then:

class Something(object):
    def __init__(self):
        self.our_random = Something.random_thing()

or call the static method after you defined it, but are still defining the class; because it is a static method, you'd have to access it through the __func__ attribute:

class Something(object):
    @staticmethod
    def random_thing():
        return 4

    our_random = random_thing.__func__()

If you didn't mean to call it, just create a copy of the method with a different name, just do so after you defined it:

class Something(object):
    @staticmethod
    def random_thing():
        return 4

    our_random = random_thing   # our_random as an alias for random_thing

The class body is executed as a function, with the local namespace of the function then forming the class attributes. So, like a function, if you want to refer to other objects you need to make sure they are defined first.

Sign up to request clarification or add additional context in comments.

Comments

2
class Something(object):
    @staticmethod
    def random_thing():
         return 4

    our_random = random_thing

Class definitions create a namespace, so you can refer to other names (class attributes) within the class body without needing to access them through the class.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.