File tree 3 files changed +62
-0
lines changed
3 files changed +62
-0
lines changed Original file line number Diff line number Diff line change @@ -115,6 +115,8 @@ The __init__ method lets the class initialize the object's attributes and serves
115
115
def __init__(self):
116
116
# body of the constructor
117
117
```
118
+
119
+ * More about __ init__ constructor [ Link] ( init_constructor )
118
120
------------
119
121
------------
120
122
#### 05. Inheritance
Original file line number Diff line number Diff line change
1
+ #!/usr/bin/env python
2
+
3
+ # init_constructor.py
4
+
5
+ # __init__() is a constructor method which helps to
6
+ # set initial values while instatiating a class.
7
+
8
+ # __init__() will get called with the attributes set in __init__(),
9
+ # when a class is instantiated.
10
+
11
+ # The '__' before and after the method name denotes that
12
+ # the method is private. It's called private or magic methods
13
+ # since it's called internally and automatically.
14
+
15
+
16
+ class Contruct (object ):
17
+ def __init__ (self ):
18
+ print ("Calling the __init__() constructor!\n " )
19
+ self .val = 0
20
+
21
+ def increment (self ):
22
+ self .val = self .val + 1
23
+ print (self .val )
24
+
25
+
26
+ dd = Contruct ()
27
+ dd .increment () # will print 1
28
+ dd .increment () # will print 2
29
+
30
+ '''
31
+ O/p-
32
+ Calling the __init__() constructor!
33
+
34
+ 1
35
+ 2
36
+ '''
Original file line number Diff line number Diff line change
1
+ #!/usr/bin/env python
2
+
3
+ # init_constructor-2.py
4
+
5
+ # We add a test in the __init__() constructor to check
6
+ # if 'value' is an int or not.
7
+
8
+
9
+ class Contruct (object ):
10
+ def __init__ (self , value ):
11
+ try :
12
+ value = int (value )
13
+ except ValueError :
14
+ value = 0
15
+ self .value = value
16
+
17
+ def increment (self ):
18
+ self .value = self .value + 1
19
+ print (self .value )
20
+
21
+
22
+ a = Contruct (10 )
23
+ a .increment () # This should print 11
24
+ a .increment () # This should print 12
You can’t perform that action at this time.
0 commit comments