This article is an example of Python object-oriented programming OOP. shared for your reference, as follows:
Classes are one of the most useful tools Python offers. When used appropriately, classes can significantly reduce development time. Classes are also used in popular Python tools, such as the tkinter GUI API.
Why Use Classes
As with object-oriented Java, classes are an abstraction of the real world.
From a more specific programming point of view, classes are Python's program composition units, like functions and modules: classes are another way to encapsulate logic and data. In fact, classes also define new namespaces, much like modules. But classes have three important unique features that make them more useful for building objects.
1. Multiple instances
Classes are basically factories that produce objects. Each time a class is called, a new object with a separate namespace is generated. Each object produced by another class reads the class properties and gets its own namespace to store data, which is different for each object.
2. Customization through inheritance
Classes also support the OOP concept of inheritance. We can extend a class by redefining its properties outside the class.
3. Operator overloading
By providing protocol-specific methods, classes can define objects that respond to several operations on built-in types. For example, objects created by classes can perform operations such as slicing, cascading, and indexing.Python provides a number of hooks that can be used by classes to interrupt and implement any of the built-in type operations.
Python's classes are similar to Java's, so the basics of inheritance, properties and methods, and classes and instances will not be covered here. The syntax content is presented directly.
Class generates multiple instance objects
[Two types of objects in the OOP model: class objects and instance objects]
Class objects provide default behavior and are factories for instance objects. Instance objects are the actual objects handled by the program: each has a separate namespace, but inherits (with automatic access) the names of variables in the class that created the instance. Class objects come from statements, while instances come from calls. Each time a class is called, a new instance of that class is obtained.
[Class objects provide default behavior]
Executing the class statement gives you the class object. The following are the main features of Python classes:
statement creates class objects and assigns them to variable names. Like function def statements, Python class statements are executable statements that, when executed, create new class objects and assign them to variable names in the class header. Also, just like the def application, the class statement is typically executed when the file it is in is imported.
Assignment statements within a class statement create attributes of the class. assignment statements at the top level within a class statement produce attributes in the class object. Technically, the scope of the class statement becomes the namespace for the attributes of the class object, just like the global scope of a module. After executing the class statement, the attributes of the class can be obtained by the variable name dot operation。
3. Class properties provide the state and behavior of an object. The properties of a class object record state information and behavior that can be shared by all instances created by the class. Function def statements located in the class generate methods, which will handle instances.
[Instance objects are concrete elements]
When the class object is called, we get the instance object. The following is a summary of the highlights contained within the instance of the class.
1. Calling a class object like a function creates a new instance object. Instances represent concrete elements in the program domain.
2. Each instance object inherits the attributes of the class and gets its own namespace. The instance object created by the class is the new namespace. It is empty at first, but inherits the properties within the class object that created the instance.
3. Assigning the self attribute within a method generates its own attribute for each instance. Within a class method function, the first argument (self) references the instance object being processed. Assigning a value to the self attribute creates or modifies data within the instance, not the class.
First example
First define a class named FirstClass and run the Python class statement through the interactive mode.
>>> class FirstClass: def setdata(self,value): = value def display(self): print()
Here it is working in interactive mode, but in general such statements should be run when the module file they are in is imported. Like a function built via def, the class doesn't exist until Python arrives and executes the statement.
Like all compound statements, class begins with a line listing the name of the class, followed by the body of one or more embedded and indented statements.
As we learned earlier, def is actually the assignment operation. Here the function object is assigned to the variable name setdata, and display lies within the scope of the class statement, thus generating the attributes attached to the class:cap (a poem)
. In fact, any variable name assigned at the top level of a class-nested block of code becomes an attribute of the class.
Functions located in a class are usually called methods. Methods when plain def, support all the elements of the function that have been learned first. In a method function, when called, the first parameter (self) automatically receives the implicit instance object: the body of the call. Two instances of this class are created below:
>>> x = FirstClass() >>> y = FirstClass()
When a class is called in this way, [note the parentheses after it], instance objects are created. To be precise, there are three objects at this point: two instances and a class.
The two instances start out empty, but they are linked to the class that created them. If you perform dot notation on the instances and on the names of the properties within the class objects, Python obtains the variable names from the class through an inheritance search.
>>> ('King Arthur') >>> (3.14159)
Neither x or y has a setdata attribute on its own, and to find this attribute, Python searches down the instance-to-class connection. And this is called Python's inheritance: inheritance occurs at the time of the attribute dot operation, and is only relevant to finding the names of variables within the connected objects.
In FirstClass's setdata function, the value passed in is assigned to the. In methods, self (which is, by convention, the name of the leftmost parameter) automatically references the instance (x or y) that is being processed, so the assignment statement stores the value in the instance's namespace, not the class's namespace.
Because the class generates multiple instances, the method must go through the self argument to get the instance being processed. When the display method of the class is called to print the contents of theWhen you do, you will find that the value is different for each instance. Also, the variable name display is the same within both x and y because it comes from the class:
>>> () King Arthur >>> () 3.14159
Attention:The data member within each instance stores different object types (strings and floats). Like everything else in Python, instance properties are not declared. After the first assignment, the instance exists, just like a simple variable. In fact, if display is called on an instance before setdata is called, the undefined variable name error is triggered: the data attribute does not exist in memory until it is assigned with the setdata method.
We can modify instance properties inside or outside the class. When inside the class, the assignment operation is performed on self through the method, while when outside the class, the assignment operation can be performed on the instance object:
>>> = 'New value' >>> () New value
Although relatively rare, by performing assignment operations on variable names outside of class method functions, we can even generate entirely new properties within the instance namespace:
>>> = 'spam'
A new attribute called anothername will be added here, and any class method of the instance object x can use it.
However, classes usually establish all the properties of an instance by performing assignment operations with the self parameter.
Class customization through inheritance
In addition to acting as a factory to generate multiple instance objects, classes can also introduce new components (subclasses) to be modified without modifying existing components in place. Instance objects generated by a class inherit the properties of that class.
In Python, instances inherit from classes, and classes inherit from superclasses. The following are the core ideas of the property inheritance mechanism:
1. Superclasses are listed in parentheses at the beginning of the class. Classes that contain inheritance are called subclasses, and the classes that subclasses inherit from are their superclasses.
2. Classes inherit attributes from their superclasses. Just as an instance inherits the names of properties defined in its class, a class inherits the names of all properties defined in its superclass. When reading a property, Python automatically searches for the property if it does not exist in a subclass.
3. EachBoth will open new independent searches.
4. The logic is modified by creating subclasses, not by modifying the superclass. By redefining the variable names of the superclasses in subclasses lower in the tree, the subclasses can replace and customize the inherited behavior.
Second example
The next example builds on the previous one. First, define a new class SecondClass that inherits all the variable names from FirstClass and provides one of its own.
>>> class secondClass(FirstClass): def display(self): print('Current value = " %s "'%)
SecondClass defines the display method to print in a different format. By defining a property with the same name as the property in FirstClass, SecondClass effectively replaces the display property within its superclass. This is because the inheritance search proceeds upward from the instance, after which it goes to the subclass and then to the superclass, until the first occurrence of the name of the property found.
Sometimes we call this redefined, property-substituting action that occurs lower in the tree [overloading]. The result is that SecondClass changes the behavior of display to particularize FirstClass. In addition, SecondClass (and any instances of it) still inherits FirstClass's setdata method:
>>> z = SecondClass() >>> (42) >>> () Current value = " 42 "
Here's a very important thing to keep in mind related to OOP: the specialization introduced by SecondClass is done entirely outside of FirstClass. That is, it does not affect currently existing or future FirstClass objects, like x in the previous example:
>>> () New value
Classes are properties within modules
There is nothing magical about the name of a class. When the class statement is executed, this is just the variable assigned to the object, which can be referenced with any ordinary expression.
For example, if FirstClass is written within a module file and not entered in interactive mode, it can be imported and its name can be used normally on the line at the beginning of the class.
from modulename import FirstClass class SecondClass(FirstClass): def display(self):...
Or, its equivalent written:
import modulename class SecondClass(): def display():...
Like everything else, class names are always present in modules. Each module can have any number of variables, functions, and classes mixed in arbitrarily. An example file is shown below:
# var = 1 def func(): ... class spam: ... class ham: ... class eggs: ...
This is also true if the module and class happen to have the same name. file, written as follows:
class person: ...
Classes need to be fetched through the module as usual:
import person x = ()
()
refers to the person class within the person module. Writing just person will only fetch the module, not the class, unless the from statement is used.
from person import person x = person()
Where Python's general conventions are concerned, class names should start with a capital letter to make them clearer:
import person x = ()
Classes can intercept Python operators: operator overloading
Operator overloading is what allows a class to be written as an object that intercepts and responds to operations used on built-in types: addition, slicing, printing, and dot notation operations.
Because of operator overloading, it is possible to make our own objects behave like built-in objects, which promotes more consistent and easier-to-learn object interfaces, and allows class objects to be handled by code that anticipates built-in type interfaces. The following is a summary of the main concepts of overloaded operators:
1. methods named with double underscores (__X__) are special hooks. the Python implementation of operator overloading is to provide specially named methods to intercept operations. the Python language defines a fixed mapping between each operation and specially named methods.
2. Such methods are automatically called when the instance appears in a built-in operation. For example, if the instance object inherits the __add__ method, the method is called when the object appears inside a + expression. The return value of the method becomes the result of the corresponding expression.
3. Classes can override most built-in type operations. There are dozens of special operator-overloaded method names that intercept and implement almost all operations of built-in types. It includes not only expressions, but also basic operations like printing and object creation.
4. Operator override methods do not have default values and are not required. If a class does not define or inherit an operator override method, it means that the corresponding operation is not supported in the class instance. For example, without __add__, the + expression raises an exception.
5. Operators allow classes to be integrated with Python's object model.
[Note, however, that operator overloading is an optional feature and is not needed for general application development unless there is a really specific need to mimic the built-in type interface.]
Third example
This time, define subclasses of SecondClass that implement three specially-named properties for Python to call automatically:
1. __init__ is called when a new instance is constructed (self is the new ThirdClass object)
2. __add__ is called when a ThirdClass instance appears in a + expression.
3. When printing an object (technically, when converting it to a print string via the str built-in function or its Python equivalent), run __str__
The new subclass also defines a conventionally named method called mul, which modifies the object of that instance in its original location. The following is a new subclass:
>>> class ThirdClass(SecondClass): def __init__(self,value): = value def __add__(self,other): return ThirdClass(+other) def __str__(self): return '[ThirdClass:%s]'% def mul(self,other): *=other >>> >>> a = ThirdClass('abc') >>> () Current value = " abc " >>> print(a) [ThirdClass:abc] >>> b = a + 'xyz' >>> () Current value = " abcxyz " >>> (3) >>> print(a) [ThirdClass:abcabcabc]
ThirdClass is a SecondClass object, so its instances will inherit the display method from SecondClass. However, calls generated by ThirdClass will now pass a parameter (e.g., 'abc'), which is passed to the parameter value within the __init__ constructor, and assign its value. The immediate effect is that ThirdClass plans to automatically set the data property at build time, rather than requesting a setdata call after the build.
In addition, ThirdClass objects can now appear in + expressions and print calls. For +, Python passes the left instance object to the self parameter in __add__ and the right value to other; what is returned by __add__ becomes the result of the + expression. For print, Python passes the object to be printed to self in __str__; the string returned by this method is treated as the object's print string. With __str__, we can display the object of the class with a regular print instead of calling the special display method.
Specially named methods like __init__, __add__, and __str__ are inherited by subclasses and instances, just like other variable names assigned in this class.Python usually calls them automatically, but occasionally they can be called by program code.
[Note: Many operator overloading methods are used only when implementing objects that are mathematical in nature. For example, vector or matrix classes may overload the addition operator, but employee classes may not. In the case of simpler classes, overloading may not be used at all.]
One overloaded method that occurs in almost every instance of a class is the __init__ constructor. Although Python does not declare the properties of an instance, it is often possible to find out what properties an instance has by finding the code for the class's __init__ method.]
Attention:There is no method overloading in Python as there is in Java, i.e., the method names are the same, but the parameters and parameter types are different, e.g., there can only be one __init__ function, take the last one assigned to the function object of __init__.
>>> class Test: def __init__(): pass def __init__(self,name,age,sex): = name = age = sex >>> a = Test() Traceback (most recent call last): File "<pyshell#54>", line 1, in <module> a = Test() TypeError: __init__() missing 3 required positional arguments: 'name', 'age', and 'sex'
After swapping the two __init__'s there is no error because the __init__ function has been changed to have no parameters:
>>> class Test: def __init__(self,name,age,sex): = name = age = sex def __init__(self): pass >>> a = Test()
The World's Simplest Python Classes
In fact, we can create classes with nothing at all; the following statement creates a class with no additional attributes within it at all:
>>> class rec:pass
Since no methods are written, we need the no-operation pass statement. After executing this statement in interactive mode and creating this class, it is possible to add attributes to this class by assigning variable names entirely outside of the initial class statement:
>>> = 'Bob' >>> = 40
After creating these attributes via assignment statements, they can be taken out using normal syntax. When used in this way, classes are almost like structs in C. We can do something similar with dictionary keys, but it requires extra characters.
>>> print() Bob
Now create two instances of this class:
>>> x = rec() >>> y = rec() >>> , ('Bob', 'Bob')
These instances have no attributes themselves; they simply take the name attribute from the class object. However, assigning an attribute to an instance creates (or modifies) the attribute within that object without initiating an inheritance search by reference to the attribute, because the attribute assignment operation only affects the object to which the attribute is assigned. Here, x gets his own name, but y still inherits the name attached to his class:
>>> = 'Gavin' >>> ,, ('Bob', 'Gavin', 'Bob')
In fact, properties of namespace objects are usually implemented as dictionaries. For example, the __dict__ attribute is a namespace dictionary for most class-based objects. As follows, the order in which names and __X__ internal name collections appear may vary with version:
>>> rec.__dict__.keys() dict_keys(['__weakref__', 'name', '__module__', '__doc__', 'age', '__dict__']) >>> list(x.__dict__.keys()) ['name'] >>> list(y.__dict__.keys()) []
Here, the class dictionary shows the name and age attributes that we have assigned, x has its own name, and y is still empty.
>>> x.__class__ <class '__main__.rec'>
Classes also have a __bases__ attribute, which is the meta-ancestor of their superclasses:
>>> rec.__bases__ (<class 'object'>,)
These two properties are Python's in-memory representation of the class tree constants.
Even methods can be created completely independently outside of an object of any class. For example, the following defines a simple function with one argument outside of any class:
>>> def upperName(self): return ()
There's absolutely nothing to do with the class here - it's a simple function that can be called at this point, as long as we pass in an object with the name attribute:.
>>> upperName(x) 'GAVIN'
However, if we assign this simple function to an attribute of the class, it becomes a method and can be called by any instance:
>>> = upperName >>> () 'GAVIN' >>> () 'BOB' >>> (x) 'GAVIN'
Relationship between classes and dictionaries
Look at the following dictionary example:
>>> rec = {} >>> rec['name'] = 'mel' >>> rec['age'] = 45 >>> rec['job'] = 'trainer/writer' >>> >>> print(rec['name']) mel
This code simulates tools like logging in other languages, and the same thing can be done here with classes:
>>> class rec:pass >>> = 'mel' >>> = 45 >>> = 'trainer/writer' >>> >>> print() 45
This code has much less syntax than its dictionary-equivalent form. It uses an empty class statement to produce an empty namespace.
This is valid, but a new class statement is required for each different record we will need. More generally, we can generate an instance of the empty class to represent each different record:
>>> class rec:pass >>> pers1 = rec() >>> ='mel' >>> = 'trainer' >>> = 40 >>> >>> pers2 = rec() >>> = 'vls' >>> = 'developer' >>> >>> , ('mel', 'vls')
Here, we populate the record by assigning values to attributes; in fact, instances of the same class don't even have to have the same set of attribute names; in this example, pers1 has the unique age attribute. Each instance has a different dictionary of attributes.
Finally, we can write a more complete class to implement logging and processing:
>>> class Person: def __init__(self,name,job): = name = job def info(self): return (,) >>> rec1 = Person('mel','trainer') >>> rec2 = Person('vls','developer') >>> >>> ,() ('trainer', ('vls', 'developer'))
Readers interested in more Python related content can check out this site's topic: thePython Object-Oriented Programming Introductory and Advanced Tutorials》、《Python Data Structures and Algorithms Tutorial》、《Summary of Python function usage tips》、《Summary of Python string manipulation techniques》、《Summary of Python coding manipulation techniquesand thePython introductory and advanced classic tutorials》
I hope that what I have said in this article will help you in Python programming.