Quantcast
Channel: What is the purpose of the `self` parameter? Why is it needed? - Stack Overflow
Viewing all articles
Browse latest Browse all 78

Answer by kmario23 for What is the purpose of the word 'self', in Python?

$
0
0

Take a look at the following example, which clearly explains the purpose of self

class Restaurant(object):  
    bankrupt = False

    def open_branch(self):
        if not self.bankrupt:
           print("branch opened")

#create instance1
>>> x = Restaurant()
>>> x.bankrupt
False

#create instance2
>>> y = Restaurant()
>>> y.bankrupt = True   
>>> y.bankrupt
True

>>> x.bankrupt
False  

self is used/needed to distinguish between instances.


Viewing all articles
Browse latest Browse all 78