Quantcast
Viewing latest article 9
Browse Latest Browse All 77

Answer by Akash Kandpal for What is the purpose of the `self` parameter? Why is it needed?

First of all, self is a conventional name, you could put anything else (being coherent) in its stead.

It refers to the object itself, so when you are using it, you are declaring that .name and .age are properties of the Student objects (note, not of the Student class) you are going to create.

class Student:    #called each time you create a new Student instance    def __init__(self,name,age): #special method to initialize        self.name=name        self.age=age    def __str__(self): #special method called for example when you use print        return "Student %s is %s years old" %(self.name,self.age)    def call(self, msg): #silly example for custom method        return ("Hey, %s! "+msg) %self.name#initializing two instances of the student classbob=Student("Bob",20)alice=Student("Alice",19)#using themprint bob.nameprint bob.ageprint alice #this one only works if you define the __str__ methodprint alice.call("Come here!") #notice you don't put a value for self#you can modify attributes, like when alice agesalice.age=20print alice

Code is here


Viewing latest article 9
Browse Latest Browse All 77

Trending Articles