Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python accessing super class variable in child class [closed]

Tags:

python

I would like to access the value of self.x in the child class. How do I access it?

class ParentClass(object):      def __init__(self):         self.x = [1,2,3]      def test(self):         print 'Im in parent class'   class ChildClass(ParentClass):      def test(self):         super(ChildClass,self).test()         print "Value of x = ". self.x   x = ChildClass() x.test() 
like image 359
user1050619 Avatar asked Aug 30 '13 15:08

user1050619


People also ask

How do you access the super class variable in a child class in Python?

Super() Function in pythonBy using the super() function, we can access the parent class members from the child class. The super() function is a built-in function, which is useful to call the superclass constructor, methods, and variables explicitly from the child class.

Can child class access instance variables of parent class?

The only unusual aspect is that, within child class method definitions, you can't directly access parent class instance variables. For example, if the parent had a height instance variable, child class method definitions wouldn't be able to access this directly.

Do child classes inherit class variables?

Classes called child classes or subclasses inherit methods and variables from parent classes or base classes. We can think of a parent class called Parent that has class variables for last_name , height , and eye_color that the child class Child will inherit from the Parent .


1 Answers

You accessed the super class variable correctly; your code gives you an error because of how you tried to print it. You used . for string concatenation instead of +, and concatenated a string and a list. Change the line

    print "Value of x = ". self.x 

to any of the following:

    print "Value of x = " + str(self.x)     print "Value of x =", self.x     print "Value of x = %s" % (self.x, )     print "Value of x = {0}".format(self.x) 
like image 189
David Robinson Avatar answered Sep 19 '22 23:09

David Robinson