0

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

2
  • I don't think that I understand your use case; perhaps you could make sure to clarify in the post when you are referring to a superclass or a subclass. Commented Nov 11, 2019 at 7:04
  • Sorry for the ambiguity in original question. I've tried to make it more clear. I'm trying to find the resolution_of_calling_class as described in the second snippet, similar to self in the first snippet refers to calling class. Commented Nov 11, 2019 at 8:11

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

Hi, that's an useful answer! I think I implemented this using Mixin pattern in my actual implementation. But this really answers the question!
@PushkarNimkar Nice!
0

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?

1 Comment

Yes B should be a child class of A as in the first example.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.