Search code examples
pythonclass-method

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


Solution

  • 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