Quantcast
Viewing all articles
Browse latest Browse all 77

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

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 77


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>