PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, July 8, 2022

[FIXED] How to access the init variable obtained from parent class into child method in python?

 July 08, 2022     class, init, methods, oop, python     No comments   

Issue

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?


Solution

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/



Answered By - Random Davis
Answer Checked By - David Marino (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing