3

I want to access a class variable defined in the parent class constructor. Here is the code.

class A(object):
    def __init__(self):
        x = 0

class B(A):
    def __init__(self):
        super(B, self).__init__()

    def func(self):
        print self.x

s = B()
s.func()

This gives me error:

AttributeError: 'B' object has no attribute 'x'

If I try changing the func() to

def func(self):
    print x

then I get error:

NameError: global name 'x' is not defined

If I try changing the func() to

def func(self):
    print A.x

Then I get the error

AttributeError: type object 'A' has no attribute 'x'

Now I am running out of ideas.. What's the correct way to access that class variable x in the parent class A? Thanks!

NOTE: I am working only on the "class B" part of my project, hence I can't really go modify class A and change the way variables are defined. That's the only constraint.

2
  • 2
    x is not a class variable. Commented Aug 20, 2016 at 19:35
  • 1
    You seem to be confusing a local variable with instance variables with class variables. Commented Aug 20, 2016 at 19:37

2 Answers 2

4

It must be self.x, not just x:

class A(object):
    def __init__(self):
        self.x = 0

Just a quick note - even from other methods of A would be the x not accessible:

class A(object):
    def __init__(self):
        x = 0
    def foo(self):
        print(self.x) # <- will not work
        print(x) # <- will utimately not work
Sign up to request clarification or add additional context in comments.

Comments

1

You need to set it as self.x = 0 instead of x = 0 - otherwise it's just a local variable.

If you cannot modify A, what you are trying to do is impossible - there is absolutely no way to access that value, not even with black magic (if your method was called by that method, you could probably do nasty things with the stack to get its value)

6 Comments

Please see the note at the bottom of my question.
In that case what you are trying to do is impossible.
AFAIK not even the blackest kind of black Python magic lets you access a local variable from a function unless it is in your call stack (which is not the case here).
I think some black magic containing a debugger and stealing the value from local namespace could do it, but that's not the way how things should be done.
But he cannot do that after the method has executed - it'll be gone. Probably you could get it from the GC but if it's really just an integer he has no way of knowing that it is the value he's looking for (for a function it'd be quite easy)
|

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.