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.

2
  • 1
    If you want to access a class attribute, why are you using a staticmethod instead of a classmethod? Commented Oct 10, 2014 at 19:16
  • oh jesus. i must have a gunshot in my brain! Commented Oct 10, 2014 at 19:20

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.