Introduction to Python
davidbpython.com
The __init__ Constructor and Object Attributes
method calls pass the instance as first (implicit) argument, called self
Object methods otherwise known as instance methods, allow us to work with the instance's data.
class Do:
def printme(self):
print(self) # <__main__.Do object at 0x1006de910>
x = Do()
print(x) # <__main__.Do object at 0x1006de910>
x.printme() # same as Do.printme(x)
- by default, 'self' is passed to every method
- the identity of 'self' can be obtained by printing it
- printing both 'self' and the instance 'x' reveal the same hex code, which is a kind of identifier for an object
- that the codes are the same indicates that self and x are the same object
- the method call can be rewritten as Class.method(instance) (see last line); this illustrates that the instance is being passed to the methods
the __init__() method
This method is automagically called when a new instance is constructed.
class Counter:
def __init__(self):
print(f'called __init__ with {self}')
a = Counter() # called __init__ with <__main__.Counter object at 0x10f8ea590>
print(a) # <__main__.Counter object at 0x10f8ea590>
- calling Counter() automatically calls the __init__() method, if it is defined
- if __init__() is not defined, it will not be called
- __init__() must be named exactly as shown to be activated
- as with all methods, the default first argument is the instance itself
using __init__() to set initial value(s) in the instance
__init__() is used to initialize the instance's attributes.
class Counter:
def __init__(self, ival): # ival: 5
self.count = ival # sets .count to 5
a = Counter(5)
print(a.count) # 5
- a value (or values) passed to Counter() is passed to __init__()
- the value is captured in a 2nd argument because the 1st argument is usually self
- the value is customarily used to initialize the instance
- by setting values in __init__(), we can guarantee that the instance has these values before anything else is done with the object
instance methods: changing instance "state"
We can use methods to modify the instance's attributes.
class Counter:
def __init__(self, ival): # ival: 0
self.count = ival # sets .count to 0
def increment(self):
self.count = self.count + 1
def get_value(self):
return self.count
a = Counter(0)
a.increment()
a.increment()
print(a.get_value()) # 2
- completing our Counter class, we now have an object that can keep track of a integer, and increment it on demand
- we can see why self is included in every method -- it is because each method is intended to either add, modify or read attributes from the instance
- we call these kinds of methods instance methods
[pr]