Python 3

home

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)


Ex. 13.7






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>


Ex. 13.8






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


Ex. 13.9






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





[pr]