Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access an instance variable of a parent class in python?

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.

like image 897
return 0 Avatar asked Jun 09 '26 03:06

return 0


1 Answers

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
like image 117
Messa Avatar answered Jun 10 '26 18:06

Messa