More on 'self'

We already know that: when defining your class methods, you must explicitly list self as the first parameter for each method, including __init__. The self means the object itself. Writing this parameter as self is a strong convention.

self signifies an instance of a class. Whenever a new instance of a class is created, self indicates that it will have its own variables that aren't shared with other instances.

In example of Apple class, when we create an object of the class, such as apple2, from outside of the class, we refer to its variables or methods using objectName.attributes such as apple2.color, apple2.say()

But when we are doing things inside a class, such as using the instance variables or calling other functions defined in the class, we use self.attributes.

To be simple, self is how we refer to things in the class from within itself.

Refer to the instance variable in a method inside the class

In Apple class, change method say() to use the instance variable:

class Apple:
    def __init__(self, color)
        self.color = color

    def say(self):
        print("I'm an apple, my color is ", self.color)

# create objects
a4 = Apple('yellow') 
a5 = Apple('pink')

print(a4.color)      # yellow
a4.say()             # I'm an apple, my color is yellow

print(a5.color)      # pink
a5.say()             # I'm an apple, my color is pink

Inside the class, in the new method say(), we access the instance variable color using code self.color.

More Example, Dog class

class Dog:
    def __init__(self, name, color):
        self.name = name
        self.color = color

    def say(self):
        print( 'Woof, Woof, I am a ', self.color, 'dog, and my name is ', self.name)

# create objects of the class
dog1 = Dog('brown', 'Max' )
print(dog1.color)      # brown
dog1.say()             # Woof, Woof, I am a brown dog, and my name is Max

dog2 = Dog('white', 'Bella' )  
print(dog2.name)          # Bella
dog2.say()                # Woof, Woof, I am a white dog, and my name is Bella

In function say(), we access the instance variables color and name using self.color and self.name.

dog1, dog2 are all instances of Dog class, they all have the variables and methods defined in the class, their variables and methods are also unique to themselves because the use of self parameter.

==

results matching ""

    No results matching ""