One of the technologies that some people haven't understood throughout their Python career: object orientation.
Python object oriented programming
To be exact, Python is also an object-oriented programming language, referred to as OOP. We already know that all data types in Python are objects. Except those set by python, python allows program developers to define data types themselves. This data type determined by programmers is a class.
There is a threshold for object-oriented beginners. Please be careful.
Class definition and use
The syntax format of class definition is as follows:
class MyClass(): Code block ... Code block
The first letter of the class name is recommended to be capitalized, such as MyClass in the syntax format.
Define classes, properties, and methods
Class contains properties and methods. Next, we define a "human" class.
# Define human class Person(): # Properties of class name = "Didi" # Class method def talk(self): print("say hello")
In the above code, Person is the name of the class in which an attribute and a method are defined. The methods defined inside a class are very similar to functions, but note that the functions defined inside a class can't be called functions (whether they start to wrap around), but should be called methods, because only the objects of the class can call this method.
When defining a method, note that one parameter is self. Remember that it is a fixed writing method. The keyword self should be written in all method parameters within the class.
Calls to properties and methods
Before calling properties and methods, you must first define an object of a class. The specific methods are as follows. This operation is also called instantiation. After the instantiation operation of a class, an object appears.
object = Class name()
For example, a human has just been defined, and the following code can be used to obtain a human object.
# Define object xiang = Person()
After the object is defined, you can use properties and methods.
class Person(): # Properties of class name = "Didi" # Class method def talk(self): print("say hello") xiang = Person() # Output object print(xiang) # Properties of the output object print(xiang.name) # Method of outputting objects xiang.talk()
After the code runs, the output is as follows.
<__main__.Person object at 0x000002465F364B70> Didi say hello
The variable xiang in the code is an object of the Person class. The name attribute and the talk method in the Person class can be read through the xiang object.
If the class has other properties and methods, it can be implemented in the same way.
Class constructor
The difficulty should be raised a little. When creating a class, you want to insert some initial data, that is, initialize the class. This content is to write a method inside the class. This method is a special method. The object defining the class will automatically execute this method during programming.
The initialization method name is fixed__ init__, This method has two underscores around init. The initialization method of a class is called a constructor (just said that it is called a method in the class, but it is called a function. Is it confused? There's really no way. Everyone calls it that).
Next, write a code to assign a value to the attribute name of the Person class by default when defining the object of a class.
class Person(): # Properties of class name = "Didi" # Constructor def __init__(self, in_name): self.name = in_name # Class method def talk(self): print("say hello") xiang = Person('teacher') # Output object print(xiang) # Properties of the output object print(xiang.name) # Method of outputting objects xiang.talk()
The above code has made some simple changes. First, it is added__ init__ Constructor. Note that there are two parameters of the constructor. One is self. This is necessary when defining a function within a class and needs to be placed on the far left of the parameter. Python will automatically pass in this parameter self when defining an object of a class. Self represents the object of the class itself.
There is also an argument in the constructor_ Name, if the constructor is designed and there are parameters other than self, the parameter must be passed when defining the Person object, and the passed parameter is passed through self Name can modify the properties of an object.
It's very simple to say. It means that every time we define an object with a class, for example, the following code:
obj1 = Person() obj2 = Person()
The above two objects are defined according to the class Person. The parameter self indicates which object it is inside the class.
If you don't understand, there's no problem. Remember the following words.
After a class is declared, it is equivalent to defining a data type yourself. You can use the variable of this data type. Just because of the object-oriented concept, this variable is called an object. An object can call the properties and methods of a class. A class corresponds to multiple objects. How to judge which object is calling the properties or methods inside the class, The parameter self is needed.
Attribute initial value
Before this section, set an initial value inside the class and directly complete it with name = "didi". After learning the constructor, you should understand that when Python initializes data, it is usually placed in__ init__ Within the method.
class Person(): # Constructor def __init__(self, in_name, in_age): # Property initialization self.name = in_name self.age = in_age # Class method def talk(self): # Class can be initialized through self Name call print(self.name) print("say hello") def show_age(self): # Through self Age call initialization age print(self.age) xiang = Person('teacher', 19) # Output object print(xiang) # Properties of the output object print(xiang.name) # Method of outputting objects xiang.talk()
encapsulation
The next step is to learn one of the three basic features of object-oriented, encapsulation.
Encapsulation, simple understanding is OK. Don't drill in first. Understand the concept and understand the concept.
The properties and methods we just used can be accessed outside the class through objects. These are called public properties and public methods. However, sometimes the properties and methods inside the class do not want to be modified by external objects. The concepts related to private properties and private methods need to be introduced. The introduction of this concept leads to the emergence of the encapsulation concept.
Encapsulation is to seal things inside a class and not let you use them casually (in fact, there are ways to call them).
Private property
Defining private attributes within a class is very simple. It is a writing skill. You only need to add two underscores in front of the attributes, namely__ name.
For example, in humans, a secret variable is defined as a private attribute.
class Person(): # Constructor def __init__(self, in_name, in_age): # Property initialization self.name = in_name self.age = in_age self.__secret = "I have code cleanliness" # Private property # Class method def talk(self): # Class to access private properties print(self.__secret) print("say hello") def show_age(self): print(self.age) xiang = Person('teacher', 19) # Attempt to output the private properties of the object print(xiang.__secret) # report errors # Try outputting private properties through the methods of the class xiang.talk()
After the private property is initialized inside the class, the object is passed Property name discovery cannot call private properties, but private properties can be used inside the class. This operation is called encapsulating properties.
Private method
If there is a private attribute, there must be a private method. These two forms are the same. Adding two underscores in front of the method is a private method.
class Person(): # Constructor def __init__(self, in_name, in_age): # Property initialization self.name = in_name self.age = in_age self.__secret = "I have code cleanliness" # Private property # Class method def talk(self): # Class to access private properties print(self.__secret) print("say hello") # Private method of class def __show_age(self): print(self.age) xiang = Person('teacher', 19) # Attempt to output the private properties of the object # print(xiang.__secret) # report errors # Try outputting private properties through the methods of the class xiang.__show_age() # report errors
Pay attention to the content of the error report, and remember it if you can remember it. The premise of skillfully finding the code error is that you encounter enough code errors.
inherit
Before learning the concept of inheritance, there are several new words to learn. First, class can be inherited. The inherited class is called parent class or base class, and the inherited class is called child class or derived class. The biggest advantage of using class inheritance is that the public properties or methods implemented by the parent class need not be redesigned in the child class.
The content is also vague. Let's take a look at the grammatical format first.
# Define a parent class class BaseClassName(): Code block of parent class class ChildClassName(BaseClassName): Code block of subclass
When inheriting a class, place the name of the parent class in parentheses.
Simple application of inheritance
Declare an animal class, and then let the dog inherit the animal class. Animal classes have a public attribute called name and a public method called sleep.
# Define an Animal class class Animal(): def __init__(self): self.name = "Animal name" def sleep(self): print("Animals sleep") # Dog class inherits from Animal class class Dog(Animal): pass dog = Dog() print(dog.name) dog.sleep()
The Dog class in the above code does not have any properties and methods. It just inherits the Animal class and has the public properties and methods of the Animal class.
In this inheritance mode, the subclass cannot directly read the private properties or methods of the parent class, that is, the following code is wrong.
# Define an Animal class class Animal(): def __init__(self): self.name = "Animal name" self.__secret = "secret" def sleep(self): print("Animals sleep") # Dog class inherits from Animal class class Dog(Animal): pass dog = Dog() print(dog.__secret) dog.sleep()
A property or method whose subclass has the same name as the parent class
When programming, subclasses can also have their own initialization methods, i.e__ init__ Method. In this case, the property name and method name in the subclass are the same as those in the parent class. In this case, please focus on the property value or method in the subclass.
# Define an Animal class class Animal(): def __init__(self): self.name = "Animal name" self.__secret = "secret" def sleep(self): print("Animals sleep") # Dog class inherits from Animal class class Dog(Animal): def __init__(self): self.name = "dog" def sleep(self): print("Dogs sleep") # Object of parent class animal = Animal() animal.sleep() # Subclass object dog = Dog() dog.sleep()
If the content is extended, it is the last of the three characteristics of object-oriented -- polymorphism.
The subclass uses the method of the parent class
Using the super function, you can call the parent class in the subclass. The specific code is as follows:
# Define an Animal class class Animal(): def __init__(self, a_name): self.name = a_name self.__secret = "secret" def sleep(self): print("Animals sleep") def show(self): print("Now the name passed in is" + self.name) # Dog class inherits from Animal class class Dog(Animal): def __init__(self, a_name): # Call the normal method of the parent object # super().sleep() super().__init__("Animal name" + a_name) # Object of parent class animal = Animal("Common animal") animal.show() # Subclass object dog = Dog("Big dog") dog.show()
In the constructor of Dog class, pass super()__ init__ ("animal name" + a_name) modifies the parameters passed to the parent class. This scheme is equivalent to generating an object of the parent class through the super function, and then calling the parent class__ init__ Method to initialize the parent class.
polymorphic
Polymorphic simple understanding means that the parent class and the child class have the same method, and the objects created by the parent class and the child class call the same method name with different results. More often, the program will automatically call the specified method according to the object. The specific code of this content is as follows:
First, define a function with one parameter.
def gogo(obj): obj.say()
The parameters of this function can be objects of any data type, and then define two classes in which the say method must exist.
class Dog(): def say(self): print("Woof, woof") class Cat(): def say(self): print("cat ") # The function will judge which method to call by the passed object. def gogo(obj): obj.say() # Define an object through Dog dog = Dog() # Define an object with Cat cat = Cat() # Pass the dog object in the gogo function gogo(dog) # Pass cat object in gogo function gogo(cat)
When the object inside the incoming function body is changed in the above code, the output data is different. This coding form or coding design idea is a display of polymorphism.
The simple understanding is that the implementation content of the same method is different due to different objects.
multiple inheritance
The above explanation is a single inheritance relationship. Multiple inheritance is often used in actual coding, that is, one class inherits multiple parent classes. The syntax structure is as follows:
class Subclass name(Parent class 1,Parent class 2,Parent class 3...): Code block for class
This content will not be expanded. In case of multiple inheritance, just remember one sentence. The parent analogy written in the front has higher priority than the parent class written in the back. That is to say, if the same method appears in the parent class, the child class gives priority to the previous parent class, that is, parent class 1 in the above syntax format.
Object data type judgment
Use the type function to determine the data type of an object, such as the following code:
class Dog(): def say(self): print("Woof, woof") class Cat(): def say(self): print("cat ") # Define an object through Dog dog = Dog() # Define an object with Cat cat = Cat() print(type(dog)) print(type(cat))
The output content is:
<class '__main__.Dog'> <class '__main__.Cat'>
type can get the source class of the object.
isinstance function
The isinstance function can judge whether an object belongs to a class. The syntax format is as follows:
isinstance(object,class) # If the object is instantiated from a class, return True; otherwise, return false
This function can determine whether an object is instantiated from its parent class.
# Parent class class Animal(): pass # Subclass class Dog(Animal): def say(self): print("Woof, woof") # Subclass class Cat(Animal): def say(self): print("cat ") # Define an object through Dog dog = Dog() # Define an object with Cat cat = Cat() print(isinstance(dog,Dog)) # True print(isinstance(dog,Animal)) # True print(isinstance(cat,Animal)) # True
Special properties and methods
In the previous lesson, using the dir function to act on an object will get the following content.
There are a lot of problems with this content__ XXXX__ These are the special properties and methods in an object.
Here are a few.
__ doc__ Get document string
If a document string is declared in a class, some contents are defined in "" quotation marks at the beginning of the class, such as the following code:
class Animal(): """" I am a document string, which is equivalent to the description part of a class. In fact, I have a standard format When the eraser snowballed for the first time, it just didn't want to write """ pass animal = Animal() print(animal.__doc__)
__ name__ attribute
Here's a question to think about, which is to consult by yourself__ name__ What does the attribute do? If you understand it, you won't ask why when you see the following code in the future.
if __name__ == '__main__': Execute some code
When the special method part snowballed for the first time, you don't have to work hard to learn. The stage hasn't arrived yet. Learning is the same as not learning. If you feel you have to learn, it happens to be an opportunity to seek knowledge. At this time, your learning will get twice the result with half the effort.
If you want to learn, you can find information by yourself. The key words are__ str__ (),__ repr__ (),__ iter__ ().
Summary of this blog
Object oriented. For beginners of programming, learning this thing is the same as not learning it. You should firmly believe that not only you can't fully master it at the first time, but 99% of people are the same. Just stick to it. First, it's enough to know that there are classes and objects in Python. Time is the biggest weapon for learning. Punch in and punch out. Learn a little every day. See you in three months.
The last bowl of poisonous chicken soup
My ex girlfriend broke up with me for two reasons. First, I didn't have much money at that time. Second, she guessed that I wouldn't have any money in the future. O(∩ \ ∩) O ha ha~