Catalog
1. Foundation of Object-Oriented Programming
"Objects are composed of a set of data structures and methods to process them. Objects with the same behavior are classified. Internal details are hidden by encapsulation of classes. Classes are specialized and generalized by inheritance and polymorphism. Orphism) implements dynamic assignment based on object type.
In short, in my opinion, object-oriented abstracts the attributes of an entity and then operates on the abstract entity, which can have a variety of behaviors (methods), rather than a simple single result.
Two very important concepts of object-oriented programming: classes and objects
Object is the core of object-oriented programming. In the process of using object, in order to abstractly define a group of objects with common characteristics and behaviors, another new concept, class, is proposed.
Class is equivalent to the drawings used to build the aircraft, and the aircraft created with it is equivalent to the object.
Relationships between classes and objects
Object-oriented has three pillars: encapsulation, inheritance and polymorphism.
2. Define classes and create objects
Define classes: class keywords can be used to define classes in Python, and then methods can be defined in classes through previously learned functions.
Define a class
class Car: # Method def getCarInfo(self): print('Number of wheels:%d, colour%s'%(self.wheelNum, self.color)) def move(self): print("The car is moving....")
Create an object
# -*- coding:utf-8 -*- """ //Define a class and create an object version:0.1 author:coke """ #class class Car: #Method def getCarInfo(self): print('Number of wheels:%d,colour%s'%(self.wheelNum,self.color)) def move(self): print("The car is moving.") BMW = Car() BMW.color = "black" BMW.wheelNum = 4 BMW.getCarInfo() BMW.move()
Note: self, the so-called self, can be understood as self. When an object calls its method, the python interpreter will pass this object as the first parameter to self, so developers only need to pass the later parameters.
3. _init_() method
In the demo in the last section, we have added two attributes to the BMW object, wheelNum and color. Imagine that if we create an object again, we must also add attributes. Obviously, it is very difficult to do so, then there is no way to create the object. By the way, how about setting the properties of the car object?
# -*- coding:utf-8 -*- """ _init_Use version:0.1 author:coke """ #Define automobile class class Car: def __init__(self): self.wheelNum = 4 self.color = 'blue' def move(self): print('The car is running, the target:Hawaii') # create object BMW = Car() print('The color of the car is:%s'%BMW.color) print('The number of tyres is:%d'%BMW.wheelNum)
Summary: When a Car object is created, BMW defaults to two attributes wheelNum and color without calling the _init_() method, because the _init_() method is called by default immediately after the object is created.
4. Magic Method
In python, if the method name is _xxxx_(), then it has special functions, so it is called "magic" method.
When you use print to output objects, as long as you define the _str_ (self) method yourself, the data return ed from this method will be printed.
# -*- coding:utf-8 -*- """ _init_Use version:0.1 author:coke """ #Define automobile class class Car: def __init__(self,newWheelNum,newColor): self.wheelNum = newWheelNum self.color = newColor def __str__(self): msg = "Vehicle tires:" + str(self.wheelNum) + " Vehicle color:" + self.color return msg def move(self): print("The car is running. Target Hawaii") BWM = Car(4,"green") BWM.move() print(BWM)
5. Visibility issues
In many object-oriented programming languages, we usually set the object's attributes as private or protected, which simply means that external access is not allowed, while the object's methods are usually public, because the public method is the message that the object can accept. In Python, there are only two kinds of access rights for attributes and methods, public and private. If you want the attributes to be private, you can start with two underscores when naming the attributes. The following code can verify this.
# -*- coding:utf-8 -*- """ //Test visibility version:0.1 author:coke """ class Test: def __init__(self, foo): self.__foo = foo def __bar(self): print(self.__foo) print('__bar') def main(): test = Test('hello') # AttributeError: 'Test' object has no attribute '__bar' test.__bar() # AttributeError: 'Test' object has no attribute '__foo' print(test.__foo) if __name__ == "__main__": main()
However, Python does not strictly guarantee the privacy of private attributes or methods in terms of grammar. It just renames private attributes and methods to "block" access to them. In fact, if you know that the rules for changing names can still access them, the following code can verify this. We are all consenting adults here. Because most programmers think that openness is better than closure, and programmers are responsible for their own actions.
# -*- coding:utf-8 -*- """ //Test visibility version:0.2 author:coke """ class Test: def __init__(self,foo): self.__foo = foo def __bar(self): print(self.__foo); print("__bar") def __str__(self): return self.__foo def main(): test = Test("hello") print(test) #In fact, the _foo attribute can be accessed externally print(test._Test__foo) if __name__ == "__main__": main()
In practical development, we do not recommend setting properties to private, because this will cause subclasses to be inaccessible (as will be discussed later). So most Python programmers follow a naming convention that allows attribute names to begin with a single underscore to indicate that attributes are protected. Codes outside this class should be cautious when accessing such attributes.
5. practice
In order to better understand object-oriented programming, the following is a case study of "roast sweet potato" for analysis.
The example attributes are as follows:
- Cooked Level: That's the number; 0-3 means raw, more than 3 means half-baked, more than 5 means baked, and more than 8 means charcoal! Our sweet potatoes start from time to time.
- cookedString: This is a string; it describes the maturity of sweet potatoes.
- condiments: Here's a list of ingredients for sweet potatoes, such as tomato sauce, mustard sauce, etc.
The example method is as follows:
- cook(): Roast sweet potatoes for a while
- addCondiments(): Adding ingredients to sweet potatoes
- _ init_(): Set default properties
- _ str_(): Make print look better
- 1. Define classes and _init_() methods
#Definition of `Digua'class class SweetPotato: 'This is the kind of roasted sweet potatoes.' #Define initialization methods def __init__(self): self.cookedLevel = 0 self.cookedString = "Raw" self.condiments = []
- 2. Method of adding "roasted sweet potato"
#Method of roasting sweet potato def cook(self, time): self.cookedLevel += time if self.cookedLevel > 8: self.cookedString = "Burnt to ashes." elif self.cookedLevel > 5: self.cookedString = "Baked." elif self.cookedLevel > 3: self.cookedString = "Halfcooked" else: self.cookedString = "Raw"
- 3. The basic functions have already been partially tested.
mySweetPotato = SweetPotato() print(mySweetPotato.cookedLevel) print(mySweetPotato.cookedString) print(mySweetPotato.condiments)
- 4. Define addCondiments() method and _str_() method
def __str__(self): msg = self.cookedString + " Sweet potato" if len(self.condiments) > 0: msg = msg + "(" for temp in self.condiments: msg = msg + temp + ", " msg = msg.strip(", ") msg = msg + ")" return msg def addCondiments(self, condiments): self.condiments.append(condiments)
All code
# -*- coding:utf-8 -*- """ //Roasted sweet potatoes """ class SweetPotato: "This is the kind of roasted sweet potatoes." #Define initialization methods def __init__(self): self.cookedLevel = 0 self.cookedString = "Raw" self.condiments = [] #How to add roasted sweet potato def cook(self,time): self.cookedLevel += time if self.cookedLevel > 10: self.cookedString = "Burnt to ashes." elif self.cookedLevel > 5: self.cookedString = "Baked." elif self.cookedLevel > 3: self.cookedString = "Halfcooked" else: self.cookedString = "Raw" #Adding ingredients def addCondiments(self,condiment): self.condiments.append(condiment) def __str__(self): msg = self.cookedString + "Sweet potato" if len(self.condiments) > 0: msg = msg + "(" for temp in self.condiments: msg = msg + temp + ", " msg = msg.strip(", ") msg = msg + ")" return msg mySweetPotato = SweetPotato() print("------With a sweet potato, it hasn't been baked yet.--------") print(mySweetPotato.cookedLevel) print(mySweetPotato.cookedString) print(mySweetPotato.condiments) print("---------Next, roast sweet potatoes.------------") print("---------The sweet potatoes were baked for four minutes.------------") mySweetPotato.cook(4) print(mySweetPotato) print("---------The sweet potatoes roasted for another minute.-----------") mySweetPotato.cook(3) print(mySweetPotato) print("----------Adding ingredient tomato sauce------------") mySweetPotato.addCondiments("Ketchup") mySweetPotato.addCondiments("Mustard") mySweetPotato.cook(2) print(mySweetPotato)
Output result