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()
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.
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.
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 .
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With