Python learning diary-Object-Oriented Programming (1), python Object-Oriented Programming
Python class and instance)
Assume that a shoe has two attributes: size and color.
Class can play a role in the template. Therefore, when creating an instance, you can forcibly enter some attributes that we think must be bound. By defining a special__init__
When creating an instance, bind the size and color attributes to shoe. For example:
1 class Shoe(object):2 3 def __int__(self, size, color):4 self.size = size5 self.color = color
(Object) indicates the class to inherit from. If there is no suitable inheritance class, the object is used;
Self indicates the instance itself. Therefore, you can use the _ int _ method to add attributes to self;
Data encapsulation
Define the function for accessing data from the class so that data can be encapsulated. For example:
1 class Shoe(object):2 3 def __init__(self, size, color):4 self.size = size5 self.color = color6 7 def get_color(self):8 print('%s: %s' % (self.size, self.color))
To define a method, except that the first parameter isself
And other functions.
To call a method, you only need to call it directly on the instance variable,self
No need to pass. Other parameters are passed in normally:
>>> bart.get_color()32: black
Another advantage of encapsulation is thatStudent
Class to add new methods, suchget_grade
:
1 class Shoe(object): 2 ... 3 4 def get_level(self): 5 if self.size >= 40: 6 return 'A' 7 elif self.size >= 32: 8 return 'B' 9 else:10 return 'C'
You can simply call get_level, for example:
>>>46.get_level()'A'
NOTE: Refer to teacher Liao Xuefeng's website http://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/001431864715651c99511036d884cf1b399e65ae0d27f7e000