''' The self is used to represent the instance of the class. With this keyword, you can access the attributes and methods of the class in python. It binds the attributes with the given arguments. The reason why we use self is that Python does not use the ‘@’ syntax to refer to instance attributes. In Python, we have methods that make the instance to be passed automatically, but not received automatically. ''' print('******Example*****') class food(): # init method or constructor def __init__(self, fruit, color): self.fruit = fruit self.color = color def show(self): print("fruit is", self.fruit) print("color is", self.color) apple = food("apple", "red") grapes = food("grapes", "green") apple.show() grapes.show() print('******Python Class self Constructor*****') ''' In the example, self refers to the name variable of the entire Person class. Here, if we have a variable within a method, self will not work. That variable is simply existent only while that method is running and hence, is local to that method. For defining global fields or the variables of the complete class, we need to define them outside the class methods. ''' class Person: # name made in constructor def __init__(self, John): self.name = John def get_person_name(self): return self.name print('******Example*****') class this_is_class: def show(in_place_of_self): print("It is not a keyword " "and you can use a different keyword") object = this_is_class() object.show()
python self method
最新推荐文章于 2021-08-20 17:40:43 发布