Pushkar Nimkar
Pushkar Nimkar

Reputation: 444

How to call class method within namespace of the same class in python 3.x

When working with python instances, it is possible to access bound methods of the same class using self. This resolves to a method corresponding to the same class in hierarchy.

class A:
    def f(self):
        return 1

    def __init__(self):
        self.v = self.f()

class B(A):
    def f(self):
        return 2

b = B()
# b.v is set to 2

But, when working with class methods, there is no apparent way of accessing methods of the same class as above.

In my use case, f above needs to be a class method and I need to set class variable v according to f corresponding to the same class. Somewhat like:

class A:
    @classmethod
    def f(cls):
        return 1

    v = resolution_of_calling_class.f()

class B(A):
    @classmethod
    def f(cls):
        return 2

# B.v should be 2

edit: v is actually an attribute defined by parent class, which should find a method overridden by child class

Upvotes: 0

Views: 324

Answers (2)

trsvchn
trsvchn

Reputation: 8981

You just need to override __new__ method, since it is invoked before the __init__ and its purpose is to create an instance, that will be initialized by __init__.

class A:

    def __new__(cls, *args, **kwargs):
        cls.v = cls.f()
        return super().__new__(cls, *args, **kwargs)

    @classmethod
    def f(cls):
        return 1


class B(A):
    @classmethod
    def f(cls):
        return 2


a = A()
print(a.v)

b = B()
print(b.v)
1
2

Upvotes: 1

Dr Code Monkey
Dr Code Monkey

Reputation: 36

I am not 100% sure I understand what you are trying to do.

I used your code above and

class A:
    @classmethod
    def f(cls):
        return 1

class B:
    @classmethod
    def f(cls):
        return 2

print(B.f())

gives me 2 just as I expected it would. Should B be a child class of A as in the first example?

Upvotes: 0

Related Questions