954,541 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

understanding the self in relation to variables

I understand that python provides a value for self when methods are called on the instance of a class.
However, I don't understand how self works when assigning value to a variable of instance.

class snake:
    def __init__(self,name):
        self.name=name#this is the bit I don't understand. How is self.name #interpreted by python?
mahela007
Posting Whiz in Training
214 posts since Feb 2009
Reputation Points: 16
Solved Threads: 2
 

Look over this code sample, it should be very explanatory:

# role of self in Python classes
# self can be named different, but 'self' is convention

class Snake:
    def __init__(self, name):
        # self keeps track of each instance
        # and also makes self.name global to class methods
        self.name = name
        # test
        print(self)

    def isnice(self):
        # a class method has self as the first argument
        return self.name + " is very nice"

# create 2 instances of class Snake
bob = Snake('Bob Python')
mary = Snake('Mary Rattle')

print('-'*40)

# now you can get the name that has been assigned to self.name
print(bob.name)
print(mary.name)

# access the class method
print(mary.isnice())

"""my result -->
# self for each instance has a different location in memory
<__main__.Snake object at 0x01E0B2B0>
<__main__.Snake object at 0x01E0B090>
----------------------------------------
Bob Python
Mary Rattle
Mary Rattle is very nice
"""
Ene Uran
Posting Virtuoso
1,723 posts since Aug 2005
Reputation Points: 625
Solved Threads: 213
 

thanks!

mahela007
Posting Whiz in Training
214 posts since Feb 2009
Reputation Points: 16
Solved Threads: 2
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You