I have a parent class and a child class where the child class inherits the init variables from the parent class using super() or Patent function. But, I am unable to access these variables inside the method of the child. How to obtain that? Here is the below code.
class Parent:
def __init__(self, item, model):
self.item = item
self.model = model
class child(Parent):
def __init__(self, item, model):
Parent.__init__(self, item, model)
print(item) # I am able to get this value
def example(self):
value = self.item * 10 # This item is not able to access and throughs an error.
print(value)
Calling child method:
child.example()
Error:
'child' object has no attribute 'item'
How to get the item variable from the parent class into the method of child class?
CodePudding user response:
The issue is how you are calling example()
:
child.example()
You're calling the example()
method of the child
class itself; you are not calling that method on an instance of child
. The class itself does not have the self.item
or self.model
properties. Those are set in the constructor (__init__()
). To call the contstructor you have to instantiate a new instance of the child
object:
c = child(10, 'blah')
Now that c
is an instance of child
, you can call example()
on the instance now:
c.example()
#output: 10
Remember, this works because c
is a reference to a specific instance of the child
class, which you deliberately created previously. child
refers to the class itself; it will not have any self
instance variables, because a class is just a class, its constructor hasn't run because it only runs when you instantiate a class, not when you deal with the class itself.
One way to avoid this issue is to adhere to the naming standards in Python. Classes always should be CamelCase
, and variables should all be snake_case
. That way, you can easily tell that child.what_ever()
is calling a method on an instance of a class, and that Child.blah_blah()
is calling a class method.
For a full list of Python naming conventions, see here: https://peps.python.org/pep-0008/