I am new to python. Im trying to access the parent class variable in child class using super() method but it throws error "no arguments". Accessing class variable using class name works but i like to know whether it is possible to access them using super() method.
class Parent(object):
__props__ = (
('a', str, 'a var'),
('b', int, 'b var')
)
def __init__(self):
self.test = 'foo'
class Child(Parent):
__props__ = super().__props__ + (
('c', str, 'foo'),
) # Parent.__props__
def __init__(self):
super().__init__()
Error:
__props__ = super().__props__ + (
RuntimeError: super(): no arguments
Accessing Parent Class Functions This is really simple, you just have to call the constructor of parent class inside the constructor of child class and then the object of a child class can access the methods and attributes of the parent class. # how parent constructors are called.
Subclasses inherit public methods from the superclass that they extend, but they cannot access the private instance variables of the superclass directly and must use the public accessor and mutator methods. And subclasses do not inherit constructors from the superclass.
__init__() Call in Python. When you initialize a child class in Python, you can call the super(). __init__() method. This initializes the parent class object into the child class. In addition to this, you can add child-specific information to the child object as well.
The super() function is used to give access to methods and properties of a parent or sibling class. The super() function returns an object that represents the parent class.
You could define an __init_subclass__
method of the Parent
class that initializes Child.__props__
. This method is called every time a subclass of of Parent
is created, and we can use it to modify the __props__
that class inherits with an optional __props__
argument passed as part of the class definition.
class Parent:
__props__ = (('a', str, 'a var'), ('b', int, 'b var'))
def __init_subclass__(cls, __props__=(), **kwargs):
super().__init_subclass__(**kwargs)
cls.__props__ = cls.__props__ + __props__
class Child(Parent, __props__=(('c', str, 'foo'),)):
pass
print(Child.__props__)
# (('a', <class 'str'>, 'a var'), ('b', <class 'int'>, 'b var'), ('c', <class 'str'>, 'foo'))
class GrandChild(Child, __props__=(('d', float, 'd var'),)):
pass
print(GrandChild.__props__)
# (('a', <class 'str'>, 'a var'), ('b', <class 'int'>, 'b var'),
# ('c', <class 'str'>, 'foo'), ('d', <class 'float'>, 'd var'))
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