In Python, names with the first letter in capital letters refer to classes. The brackets in this class definition are empty because we are creating this class from blank space. We wrote a docstring describing the functionality of this class. Functions in a class are called methods.
Taking the Student class as an example, in Python, defining a class is through the class keyword:
class Student(object) : Pass |
Class is followed by the class name, namely Student. The class name is usually a word starting with a capital letter, followed by ( object), indicating which class the class inherits from. Usually, if there is no suitable inheritance class, the object class is used. This is the class that all classes will eventually inherit.
class Student(object):
def __init__( self, name, score): __init__() is a special method that Python automatically runs whenever a new instance is created. There are two underscores at the beginning and end. This is a convention designed to avoid name conflicts between Python default methods and ordinary methods. In the definition of this method, theformal parameter self is essential and must be located before other formal parameters. |
4.self.name= name Variables like this that can be accessed through instances are called attributes 5. An important feature of object-oriented programming is data encapsulation. You can directly define functions for accessing data inside the class, thus encapsulating the "data". These functions that encapsulate data
are associated with the Student class itself, which we call methods of the class.9.1.2 Create an instance based on the class We usually You can think of a name with the first letter in uppercase (such as Dog) as referring to the class, while a lowercase name (such as my_dog) refers to the instance created from the class. 1. To access the attributes of the instance, you can use theperiod notation. We wrote the following code to access the value of the attribute name of my_dog.
My_dog.name The period notation is very commonly used in Python. This syntax demonstrates how Python learns the value of an attribute. 2. After creating an instance based on the Dog class, you can use period notation to call any method defined in the Dog class.3. Any number of instances can be created based on the class as needed.
9.2 Using classes and instances 1. An important task you need to perform is to modify the properties of the instance. You can modify the properties of an instance directly, or you can write methods to modify them in a specific way. 2. A class is a template for creating an instance, and an instance is a specific object. The data owned by each instance is independent of each other and does not affect each other; the method is the function bound to the instance, and the ordinary function Differently, methods can directly access the data of the instance; by calling the method on the instance, we directly operate the data inside the object, but there is no need to know the implementation details inside the method. Unlike static languages, Python allows any data to be bound to instance variables. That is to say, for two instance variables, although they are different instances of the same class, they may have different variable names. 9.2.1 Set an initial value for the class Every attribute in the class must have an initial value, even if the value is 0 or an empty string. In some cases, such as when setting a default value, it is possible to specify such an initial value within the __init__() method; if you do this for an attribute, you do not need to include formal parameters that provide it with an initial value. Define attributes directly in class, which are class attributes: class Student(object): name = 'Student'
class Student(object): def __init__(self, name, score): self.__name = name # Self .__ SCORE = Score DEF PRINT_SCORE (SELF): Print (' %s: %s' %(seld .__ name , self.__score)) |
3. After the change, there are no changes to the external code, but the instance variables .__name and .__name are no longer accessible from the outside. Instance variable .__score:
##>>> bart = Student('Bart Simpson', 98)>> ;> bart.__nameTraceback (most recent call last): File " |
class Student(object): ... def get_name(self): return self.__name def get_score(self): return self.__score |
class Student(object): ... def set_score(self, score): self.__score = score |
... def set_score(self, score): if 1 ## 7. It should be noted that in Python, variable names are similar to __xxx__, that is, starting with a double underscore and ending with a double underscore, they are special variables. Special variables can be accessed directly and are not private. variables, so variable names such as __name__ and __score__ cannot be used. Sometimes, you will see instance variable names starting with an underscore, such as _name. Such instance variables can be accessed externally. However, according to the convention, when you see such a variable, it means That is, "Although I can be accessed, please treat me as a private variable and do not access it at will." 8. Instance variables starting with a double underscore are not necessarily inaccessible from the outside. The reason why __name cannot be accessed directly is that the Python interpreter externally changes the __name variable to _Student__name, so the __name variable can still be accessed through _Student__name. 9.3 Inheritance1. If a class is similar to a special version of another class, you can use inheritance. If a class inherits another class, it will automatically obtain all the properties and methods of the other class. The original class is the parent class, and the new class is the child class. 2. The subclass inherits all the attributes and methods of the parent class, and can also define its own attributes and methods. In OOP programming, when we define a class, it can inherit from an existing class. The new class is called a subclass (Subclass), and the inherited class is called a base class, parent class or super class. (Base class, Super class).
9.3.1 Subclass method __init__()1. Inheritance requires assigning values to all attributes of the parent class, and the __init__() of the subclass requires help from the parent class. 2. And the parent class must be in the inheritance file, before the child class. 3. When defining a subclass, the name of the parent class must be specified in parentheses. 4.super() special function helps Python connect parent classes and subclasses in parallel. The parent class is also called the super class, the origin of super. 9.3.2 Define methods and attributes of subclassesLet a class inherit from another class. Properties and methods that distinguish subclasses from parent classes can be added. 9.3.3 Rewriting the parent classMethods corresponding to the parent class can be rewritten only if they do not meet the needs of the subclass. Add new methods to the subclass to describe the characteristics of the subclass. . Get rid of the worst of the parent category and take the best. 9.3.4 Polymorphism1. When the same method exists in both the subclass and the parent class, we say that the subclass overrides the method of the parent class. When the code is running, Subclass methods are always called. In this way, we gain another benefit of inheritance: polymorphism 2. Therefore, in the inheritance relationship, if the data type of an instance is a subclass, its data type can also be regarded as Is the parent class. However, the reverse is not true. 3. The advantage of polymorphism is that when we need to pass in Dog, Cat, Tortoise..., we only need to receive the Animal type, because Dog, Cat, Tortoise... are all Animal types , and then just operate according to the Animal type. Since the Animal type has a run() method, any type passed in, as long as it is an Animal class or subclass, will automatically call the run() method of the actual type. This is what polymorphism means. 4. For a variable, we only need to know that it is of Animal type, without knowing exactly its subtype, we can safely call the run() method, and the specific run() method called is the function Whether on an Animal, Dog, Cat or Tortoise object is determined by the exact type of the object at runtime. This is the real power of polymorphism: the caller only cares about the call, regardless of the details, and when we add a new subclass of Animal, Just make sure the run() method is written correctly, regardless of how the original code is called. This is the famous "open and closed" principle:
9.3.5 Using __slots__In order to achieve the purpose of restriction, Python allows you to define a special __slots__ variable when defining a class to limit the Attributes that can be added to class instances.
When using __slots__, please note that the attributes defined by __slots__ only affect the current class instance and have no effect on inherited subclasses. 9.3.6 Multiple inheritance1. Through multiple inheritance, a subclass can obtain all the functions of multiple parent classes at the same time. 2. When designing the inheritance relationship of a class, usually the main line is inherited from a single source. For example, Ostrich inherits from Bird. However, if you need to "mix in" additional functionality, you can achieve it through multiple inheritance. For example, let Ostrich inherit Runnable in addition to inheriting from Bird. This design is often called MixIn. The purpose of MixIn is to add multiple functions to a class. In this way, when designing a class, we give priority to combining multiple MixIn functions through multiple inheritance instead of designing multi-level complex inheritance relationships. 3. In this way, we do not need a complicated and huge inheritance chain. As long as we choose to combine the functions of different classes, we can quickly construct the required subclasses. Since Python allows multiple inheritance, MixIn is a common design. Languages that only allow single inheritance (such as Java) cannot use MixIn's design. 9.3.7 Customized classes1. There are many special-purpose functions in Python classes that can help us customize classes. __str__After defining the __str__() method, you can return a nice-looking string:
The solution is to define another __repr__(). But usually the codes of __str__() and __repr__() are the same, so there is a lazy way to write it:
|
The above is the detailed content of Introduction to basic learning of Python. For more information, please follow other related articles on the PHP Chinese website!