0

I really don't know how to describe this problem good enough. So i think an example is more expressive:

class A:
    c=1
    @staticmethod
    def b(): return A.c

class B(A):
    c=2

I hope B.b() returns 2. but the reality is it does not. in which way am i gonna achieve it? Thanks a lot.

Jason Hu
  • 6,239
  • 1
  • 20
  • 41

2 Answers2

2

You'd have to use a class method, so you could reference the class dynamically. A static method like you are currently using is not bound to any class, so you have to statically explicitly reference the A class as you are.

class A(object):
    c = 1
    @classmethod
    def b(cls):
        return cls.c

class B(A):
    c = 2
Silas Ray
  • 25,682
  • 5
  • 48
  • 63
2

The problem is that you're using a staticmethod, and hardcoding the class A, instead of using a classmethod, and using the cls argument.

Try this:

class A:
    c=1
    @classmethod
    def b(cls): return cls.c

The docs (linked above) explain the difference, but you may want to try looking at Stack Overflow questions like What is the difference between @staticmethod and @classmethod in Python for a more in-depth discussion. Briefly: a staticmethod is basically just a global function inside the class's namespace, while a classmethod is a method on the class object; if you want to use any class attributes (or the class itself, as in the alternate constructor idiom), you want the latter.

Community
  • 1
  • 1
abarnert
  • 354,177
  • 51
  • 601
  • 671