0

I am creating a couple of 'Child' classes which are quite similar and thus wanted to group common methods in a parent class. My problem comes when trying to access static variables of the child classes from the super class.

The following code throws the error: NameError: name 'var' is not defined

class Parent:
    @staticmethod
    def do_something_with_var():
        print(var)

class Child(Parent):
    var = "Hello world"

Child.do_something_with_var()

Next thing I tried was obviously to declare var in Parent, but the same error persists.

class Parent:
    var = ""

    @staticmethod
    def do_something_with_var():
        print(var)

class Child(Parent):
    var = "Hello world"

Child.do_something_with_var()

A solution that I found was to receive the sender class, but then the call becomes a bit ugly:

class Parent:
    @staticmethod
    def do_something_with_var(cls):
        print(cls.var)

class Child(Parent):
    var = "Hello world"

Child.do_something_with_var(Child)

2 Answers 2

3

You are confused over the usage of staticmethods(your third attempt), accessing class variables (second attempt).

What you want to do is classmethods, as shown under (Python 2.7):

class Parent(object):
    @classmethod
    def do_something_with_var(cls):
        print cls.var

class ChildA(Parent):
    var = "Child A"

ChildA.do_something_with_var()  # prints Child A

This example is equivalent to your third attempt.

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

1 Comment

Oh, I actually tried your solution but I was still providing Child as an argument... All clear now!
1

Static scoping of the method means it is bound to the class scope as a namespace, without any reference to the class.

What you need is to have a @classmethod, so that you are able to get a reference to the class.

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.