Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Coding using class
#1
#!/usr/bin/python3

class Parent:
    def _init_(self,x):
        self.x=x

    def count(self,x):
        self.x = self.x + 1

class Child(Parent):
    def _init_(self, y=0):
        Parent._init_(self,3)
        self.y = y

    def count(self):
        self.y +=1

obj=Child()
obj.count()
print(obj.x,obj.y)
I am using class in this code and I would like to see what: print(obj.x, obj.y) yields. However, I get this error:
Error:
Traceback (most recent call last): File "./code_with_class.py", line 19, in <module> obj.count() File "./code_with_class.py", line 16, in count self.y +=1 AttributeError: 'Child' object has no attribute 'y'
What do I need to do to correct this? How can I improve this code?
Larz60+ write Oct-27-2020, 04:48 PM:
Please post all code, output and errors (it it's entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.

I added for you this time, Please use in all future posts.
Reply
#2
not that it is __init__() - i.e. with double underscores.
In your code you use single underscore and thus [both] _init_ are not called at all
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
_init_ is a function with a funny looking name.

__init__ is a special function that is automatically called when you create a new instance of a class.

The double underscore is used to mark these special functions (often called "dunders"). For many Python programmers the only dunder they will ever use is __init__.

It is important to note that the double underscore is not what makes the function special. Python has decided what the special functions are and uses the double underscore naming convention to make these functions easy to spot and less likely to collide with function/method names in user code.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Subclass initialized property used in parent class method. Is it bad coding practice? saavedra29 5 1,853 Feb-07-2022, 07:29 PM
Last Post: saavedra29

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020