Simon
Simon

Reputation: 762

Python referencing static methods within a class - best practise

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.

Upvotes: 0

Views: 109

Answers (1)

mgilson
mgilson

Reputation: 310307

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.

Upvotes: 1

Related Questions