0

This is just an "Is there a better way of doing x?" question about @staticmethod functions in classes using python.

I have the following:

class my_class():
    @staticmethod
    def function_a():
        print("hello")

    @staticmethod
    def function_b():
        my_class.function_a()

Obviously with static classes you have no "self" reference, but is there another way to reference functions inside a class without using the class name "my_class.xxxxx"?

Most other languages have a different version, for example php has $this-> for inheritance and self:: for static.

1 Answer 1

1

my_class.function_b should be a classmethod:

@classmethod
def function_b(cls):
    cls.function_a()

classmethods get passed a reference to the class that they are called on (or the class of the instance that they are called on) as the first argument rather than the usual self.

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

2 Comments

So you cant reference any other way with static methods, you can only reference with the full class name? And class methods are the best way to do a staticmethod when you dont want to reference the classname? (just want to make sure its the best and only option)
Not sure what you mean. But, with python, there are no hidden variables that just happen to be there (e.g. implicit this, or arguments or ...). With python, the namespace consists of the enclosing namespace (e.g. stuff picked up via closure) and the stuff passed into the function + locals that the function defines itself. If you want to reference other methods on the class, (without naming the class explicitly) you need a classmethod or an instance method. You can't do it from a staticmethod.

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.