Python Forum

Full Version: Coding using class
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
#!/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?
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
_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.