In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces "how to understand the class and modularization of Python". In the daily operation, I believe that many people have doubts about how to understand the class and modularization of Python. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the doubt of "how to understand the class and modularization of Python". Next, please follow the editor to study!
Learning goal
Python is a concise, easy to learn, object-oriented programming language. It not only has powerful native data types, but also provides easy-to-use control statements. The main goal of this section is to introduce the object-oriented programming paradigm and modularization ideas in Python, so as to lay the foundation for the following study. This paper will fully introduce the basic knowledge and basic ideas of Python needed to learn data structures and algorithms, and give corresponding examples and explanations.
Master the basic concepts of Python object-oriented programming and write Python custom classes
Master the programming idea of Python modularization
1. Object-oriented programming: the basic concept of Class 1.1 object-oriented programming
A perfect program is made up of data and instructions. Procedural programming uses the idea of "divide and conquer" and uses functions to deal with data. the relationship between data and functions is loose, that is, the same data can be accessed by all functions in the program. and a function can also access different data in the program. As a result, if an exception occurs, you need to look for the error code throughout the system.
In order to solve this problem, object-oriented programming (Object Oriented Programming, OOP) divides the system into different objects, each of which contains its own information data and the methods to operate the data. For example, each string object has character data, as well as methods to change case, find, and so on.
Object-oriented programming uses classes to describe the common properties (attributes) of all objects it contains, namely data attributes (also known as data members or member variables) and functional properties (also known as member functions or methods).
The object of a class is also called an instance of this class. For example, 32 is an object of integer class int, and you can use the function type () to get the class to which the object belongs:
> > type (32)
You can query the properties of a class using the built-in function dir ():
> dir (32) ['_ _ abs__','_ _ add__','_ _ and__','_ _ bool__','_ _ ceil__','_ _ class__','_ _ delattr__','_ _ dir__','_ _ divmod__','_ doc__','_ eq__','_ float__','_ _ floor__','_ _ floordiv__' '_ _ format__',' _ _ ge__','_ _ getattribute__','_ _ getnewargs__','_ _ gt__','_ _ hash__','_ _ index__','_ _ init__','_ _ init_subclass__','_ _ int__','_ invert__','_ le__','_ lshift__','_ _ lt__' '_ _ mod__',' _ _ mul__','_ _ ne__','_ _ neg__','_ _ new__','_ _ or__','_ _ pos__','_ _ pow__','_ _ radd__','_ _ rand__','_ rdivmod__','_ reduce__','_ reduce_ex__','_ _ repr__' '_ _ rfloordiv__',' _ _ rlshift__','_ _ rmod__','_ _ rmul__','_ _ ror__','_ _ round__','_ _ rpow__','_ _ rrshift__','_ _ rshift__','_ _ rsub__','_ rtruediv__','_ rxor__','_ setattr__','_ _ sizeof__' '_ str__',' _ _ sub__','_ _ subclasshook__','_ _ truediv__','_ _ trunc__','_ _ xor__', 'as_integer_ratio',' bit_length', 'conjugate',' denominator', 'from_bytes',' imag', 'numerator',' real', 'to_bytes']
Before continuing, let's take a quick look at the three major features of object-oriented-polymorphism, encapsulation, and inheritance.
1.1.1 Polymorphism
Polymorphism: you can perform the same operation on different types of objects.
Polymorphism is actually very common. For example, both list objects and tuple objects have count methods. When we use variables to call the count method, we do not need to know whether it is a list or a tuple. This is the role of polymorphism. This not only applies to methods, but many built-in operators and functions also use polymorphism:
1.1.2 Encapsulation
Encapsulation: hides the details about the specific operation of the object from the outside.
For example, we take the real part and imaginary part of the imaginary number as the data attributes of the object, that is, we "encapsulate" the properties of the object in the object.
1.1.3 inheritance
Inheritance: used to establish a hierarchy of classes and create new classes based on the upper classes.
If we have some classes, and when we create a new class, we find that it is very similar to the existing class, only need to add some new methods, then we may not want to copy the code of the old class to the new class, then we will use inheritance.
1.2 Custom CLA
We already know that an abstract data type is a collection of objects and operations on an object, which are bundled as a whole, using not only the data properties of the object, but also the operations on the object. An operation (called a method in a class) defines an interface between an abstract data type and the rest of the program. The interface defines what the operation is to do, but does not specify how to do it, so we can say that the fundamental goal of the abstraction is to hide the details of the operation. Classes are designed to implement data abstract types.
Python defines a class with the keyword class in the following format, where the method definition is similar to the function definition syntax:
Class class name:
Method definition
Next, build a class that implements the abstract data type Imaginary (imaginary number) to show how to implement a custom class.
When defining a class, you first need to provide a constructor, which defines how the data object is created. To create an Imaginary object, you need to provide both the real part and the imaginary part of the data. In Python, _ _ init__ () is the constructor name:
Class Imaginary: def _ _ init__ (self, real, imag): self.real = real self.imag = imag
The first item of the formal parameter list is a special parameter that points to the object itself (self is usually used). When calling, you do not need to provide the corresponding actual parameters, but the remaining parameters in the construction method must provide corresponding arguments, so that the newly created object can know its initial value. Like the function definition, you can provide default arguments for the parameters through default values. For example, in the Imaginary class, self.real defines that the Imaginary object has an internal data object named real as its real data property, while self.imag defines the imaginary part.
When you create an instance of the Imaginary class, the constructor defined in the class is called, using the class name and passing in the actual value of the data attribute:
> imaginary_a = Imaginary (6,6) > imaginary_a
The above code creates an object named imaginary_a with a value of 6room6i, which is an example of encapsulation that packages data properties and methods that manipulate data properties in the object.
In addition to instantiation, the class supports another operation: property references (including data and functional attributes), and access to the properties associated with the class through dot markup:
> > imaginary_a.real6 > imaginary_a.imag6
In addition to data attributes, you also need to implement the methods (functional properties) required for abstract data types, keeping in mind that the first parameter of the method, self, is essential, such as printing an instantiated imaginary object and writing a class method display ():
Class Imaginary: def _ init__ (self, real, imag): self.real = real self.imag = imag def display (self): print ('{} {: +} i'.format (self.real, self.imag))
Call the class method to print the instantiated imaginary object:
> imaginary_a = Imaginary (6,6) > imaginary_a.display () 6i > print (imaginary_a)
As you can see, if you use the print () function to print only the address stored in a variable, this is because the default implementation of _ _ str__ (), which converts an object to a string, returns the address string of the instance. If you want to print the object using the print function, you need to override the default _ _ str__ () method, or overload it:
> imaginary_a = Imaginary (6,6) > imaginary_a.display () 6i > print (imaginary_a)
If you use the print () function again, you can print the object directly:
> imaginary_a = Imaginary (6,6) > print (imaginary_a) 6146i
Can overload many methods in the class, the most common is the overload operator, this is because people are used to using familiar operators on the data, which is more intuitive and easy to understand than using functions, such as the expression: 8 + 6 / 3, if the function is: add (8, div (6,3)), obviously the former is more in line with the habit than the latter. If a certain type of object wants to use common operators, it must redefine the corresponding operator functions for that type. For example, Python redefines multiplication operator functions for int integers, float floating-point types, str string types, and so on, and redefines operator functions for a type, also known as operator overloading. We can write the _ _ mul__ () method of the Imaginary class to overload the multiplication:
Class Imaginary: def _ init__ (self, real, imag): self.real = real self.imag = imag def display (self): print ('{: +} i'.format (self.real, self.imag)) def _ str__ (self): print ('{: +} i'.format (self.real, self.imag)) def _ mul__ (self) Other): new_real = self.real * other.real-self.imag * other.imag new_imag = self.real * other.imag + self.imag * other.real return Imaginary (new_real, new_imag)
You can also overload other operators, such as the comparison operator = =, that is, the _ _ eq__ () method, which overloads the Imaginary class's _ _ eq__ () method, which allows two imaginary numbers to be compared to see if their values are equal, which is also called deep equality; while shallow equality is judged by reference, only two variables are equal if they are references to the same object:
# shallow_and_deep_equal.pyclass ImaginaryFirst: def _ init__ (self, real, imag): self.real = real self.imag = imag def display (self): print ('{: +} i'.format (self.real, self.imag)) def _ str__ (self): print ('{} {: +} i'.format (self.real) Self.imag) class Imaginary: def _ init__ (self, real, imag): self.real = real self.imag = imag def display (self): print ('{: +} i'.format (self.real, self.imag)) def _ str__ (self): print ('{: +} i'.format (self.real, self.imag)) def _ eq__ (self) Other): return self.real = = other.real and self.imag = = self.imagprint ('shallow equivalent: only two variables are equal if they are references to the same object.') Imag_1 = imag_2 = ImaginaryFirst (6,6) print ('imag_1 = = imag_2', imag_1 = = imag_2) imag_1 = ImaginaryFirst (6,6) imag_2 = ImaginaryFirst (6,6) print ('imag_1 = = imag_2', imag_1 = = imag_2) print ('deep equality: the equality of two variables means that the object is equal.') Imag_1 = imag_2 = Imaginary (6,6) print ('imag_1 = = imag_2', imag_1 = = imag_2) imag_1 = Imaginary (6,6) imag_2 = Imaginary (6,6) print ('imag_1 = = imag_2', imag_1 = = imag_2)
The running result of the program is as follows:
Shallow equality: only two variables are equal if they are references to the same object.
Imag_1 = = imag_2 True
Imag_1 = = imag_2 False
Deep equality: the equality of the values of two variables means that the objects are equal.
Imag_1 = = imag_2 True
Imag_1 = = imag_2 True
1.3 talk about inheritance again
1.3.1 inheriting instances
Inheritance can establish a set of abstractions related to each other, and can establish a hierarchy of classes, which is also called inheritance hierarchy, and each class can inherit properties from the upper class. In Python, the object class is at the top level.
The new class at the lower level inherits the properties of the existing class and adds some of its own unique properties. this new class is called "derived class" or "subclass", while the original class is called "base class", "parent class" or "superclass". To define a subclass with a parent class, you need to add parentheses after the defined class name, and write the parent class name in parentheses. If the parent class of a class is not explicitly stated, the parent class is object by default.
For example, triangles include acute triangles, right triangles and obtuse triangles, so when defining classes, we can define not only the Triangle of general triangles, but also the AcuteTriangle of acute triangles. Then we can make the AcuteTriangle class inherit the Triangle class:
Class Triangle: def _ init__ (self, edge_1, edge_2, edge_3): self.edge_1 = edge_1 self.edge_2 = edge_2 self.edge_3 = edge_3 def _ str__ (self): return str ((self.edge_1, self.edge_2) Self.edge_3) def print_info (self): print ('The three sides of a triangle are {}, {} and {}' .format (self.edge_1, self.edge_2, self.edge_3)) def perimeter (self): return self.edge_1 + self.edge_2 + self.edge_3 class AcuteTriangle (Triangle): def _ init__ (self, edge_1, edge_2, edge_3) Max_angle): # initialize Triangle.__init__ (self, edge_1, edge_2) with the parent class constructor Edge_3) self.max_angle = max_angle def print_info (self): Triangle.print_info (self) print ('The max angle is {}' .format (self.max_angle)) def get_max_angle (self): return self.max_angle
You can see that in addition to inheritance, subclasses can also:
Add new attributes, such as data property max_angle and method property get_max_angle, added to the subclass AcuteTriangle
Replace (override) attributes in the parent class, such as AcuteTriangle overrides the _ _ init__ () and print_info () methods of the parent class. Take the AcuteTriangle.__init__ () method as an example, first call Triangle.__init__ () to initialize the inherited instance variable self.edge_1,self.edge_2,self.edge_3, and then initialize self.max_angle, which is available only in the AcuteTriangle instance, but not in the Triangle instance.
> triangle_a = Triangle (3,4,6) > triangle_a.print_info () The three sides of a triangle are 3,4 and 6 > triangle_b = AcuteTriangle (3,3,3,60) > triangle_b.print_info () The three sides of a triangle are 3,3 and 3The max angle is 60
You can call the method of the parent class through the super () method in the subclass, which omits the parent class name:
Class AcuteTriangle (Triangle): def _ _ init__ (self, edge_1, edge_2, edge_3, max_angle): # initialize super (). _ _ init__ (self, edge_1, edge_2) with the parent class constructor Edge_3) self.max_angle = max_angle def print_info (self): super () .print_info (self) print ('The max angle is {}' .format (self.max_angle)) def get_max_angle (self): return self.max_angle
Use the built-in function isinstance () to check whether an object is an instance (object) of a class, and to determine whether a class is a subclass of another class, you can use the built-in method issubclass ():
> triangle_a = Triangle (3,4,6) > triangle_b = AcuteTriangle (3,3,3,60) > print (isinstance (triangle_a, Triangle)) True > print (isinstance (triangle_a, AcuteTriangle)) False > > print (isinstance (triangle_b, AcuteTriangle) True > print (isinstance (triangle_b, Triangle) True > > print (issubclass (AcuteTriangle, Triangle)) True > > print (issubclass (Triangle, AcuteTriangle) False)
Because the class AcuteTriangle is derived from the class Triangle, an AcuteTriangle-like object is certainly a Triangle-like object, just as "an acute triangle is also a triangle."
1.3.2 multiple inheritance
A class can inherit the properties of multiple classes, which is also called multiple inheritance, for example:
Class RightTriangle (Triangle): def area (self): return self.edge_1 * self.edge_2 * 0.5 def print_name (self): print ('This is a right triangles') class IsoscelesTriangle (Triangle): def print_name (self): print ('This is an isosceles triangles') class IsoscelesRightTriangle (RightTriangle, IsoscelesTriangle): pass
In the above example, the pass statement does nothing and acts as a placeholder to wait for subsequent supplementary code; it can also be used where the statement is syntactically required but no work is actually needed.
two。 Module
We already know that functions and classes are blocks of code that can be called repeatedly. The way to use code blocks located in different files in a program is to import the module (mudule) in which the object is located.
In the previous example, we always used shell, or assumed that the entire program was saved in a file, which might not be a problem when the program was relatively small. However, as the program becomes larger and larger, it is usually more convenient to save different parts of the program in different files according to different classification methods.
2.1 Import Modul
The Python module allows us to easily build programs using code from multiple files. A module is a .py file that contains Python definitions and statements.
For example, if we create a hello_world.py file, we can understand that we have created a module called hello_world:
# hello_world.pydef print_hello (): print ('Hello wordstones') class Triangle: def _ init__ (self, edge_1, edge_2, edge_3): self.edge_1 = edge_1 self.edge_2 = edge_2 self.edge_3 = edge_3 def _ str__ (self): return str ((self.edge_1, self.edge_2) Self.edge_3)) def print_info (self): print ('The three sides of a triangle are {}, {} and {}' .format (self.edge_1, self.edge_2, self.edge_3)) def perimeter (self): return self.edge_1 + self.edge_2 + self.edge_3
You can think of a module as an extension. To import a module, you need to use the keyword import. The general format of the import module is as follows:
Import module_1 [, module_2....] # can import multiple modules at the same time
For example, to import the hello_world module in the test.py file:
Import hello_world
Imported modules only need to specify the module name and do not need and cannot have the file extension .py. If you want to use objects in a module, such as functions, classes, etc., you need to use the period operator (.), even if you use the module name. object to access. For example, use hello_worl.Triangle to access the class Triangle in the module hello_world:
# test_1.pyimport hello_worldhello_world.print_hello () tri_a = hello_world.Triangle (3,4,5) print (tri_a)
The program output is as follows:
Hello World!
(3, 4, 5)
It is important to note that the imported modules must be under the same directory hierarchy, otherwise you need to add a directory structure, for example, if hello_world is under the subdirectory module, you need to use the following methods:
# test_2.pyimport module.hello_worldmodule.test.print_hello ()
The program output is as follows:
Hello World!
2.2 Import Python standard module
Python provides many standard modules, and these module files are located in the lib folder of the Python installation directory. You can import a standard module like a module you wrote yourself, such as an math module, using objects in it:
# test_3.pyimport mathprint ('sqrt (4) =', math.sqrt (4)) print ('sin (π / 6) =', math.sin (math.pi / 6))
The program output is as follows:
Sqrt (4) = 2.0
Sin (π / 6) = 0.499999999999994
Here you may have a question, the imported module and the current file are not in the same directory, why not use the module path? This question can also be translated into-- how does the Python interpreter find the corresponding file when we use the import statement?
This involves the search path of Python, which consists of a series of directory names from which the Python interpreter looks for the introduced modules. The search path is stored in the path variable in the sys module:
> > import sys > sys.path ['','D:\\ Program Files\\ Python39\\ python39.zip', 'D:\\ Program Files\\ Python39\\ DLLs', 'D:\\ Program Files\\ Python39\\ lib', 'D:\\ Program Files\\ Python39', 'D:\\ Program Files\\ Python39\\ lib\\ site-packages'2.3 imports the required objects in the module separately
We may not want to specify the module name every time an object in the module is called, so we can use from module import object to import the desired object separately from the module, and there is no need to add the "module name" before using this separately imported object. Prefix:
# test_4.pyfrom math import pi, sinprint ('sqrt (4) =', sqrt (4)) print ('sin (π / 6) =', sin (math.pi / 6)) 2.4 Import all objects in the module
All objects in the module can be imported through from module import *, and the module name prefix is no longer required:
# test_5.pyfrom math import * print ('sqrt (4) =', sqrt (4)) print ('sin (π / 6) =', sin (math.pi / 6))
Different program code may inevitably use the same name to name different objects, which will cause conflicts, but if these names belong to different modules, they can be distinguished by module names, so in order to avoid name conflicts, you should try to avoid using from module import object or from module import * to import objects.
2.5 rename the import module or object
Another way to avoid name conflicts is to rename the import module or object:
# test_6.pyimport math as mfrom datetime import date as dprint (d.today ()) print ('sqrt (4) =', m.sqrt (4)) print ('sin (π / 6) =', m.sin (math.pi / 6))
The program output is as follows:
Datetime.date (2021, 12, 3)
Sqrt (4) = 2.0
Sin (π / 6) = 0.499999999999994
You can see that the additional benefit is that abbreviations can be used to reduce the coding effort.
2.6 Import third-party modules
In addition to the standard library, Python also has a large-scale third-party library, covering almost all areas of information technology, which is one of the great advantages of Python. The following is to take the common visualization library matplotlib as an example to introduce the use of third-party libraries. Unlike standard libraries, third-party libraries need to be installed first, and you can quickly install the required libraries by using the pip command in the shell command:
Pip install matplotlib
After installation, there is no difference between using a third-party library and a standard library:
# cos_1.pyimport mathfrom matplotlib import pyplot as pltscale = range (100x) x = [(2 * math.pi * I) / len (scale) for i in scale] y = [math.cos (I) for i in x] plt.plot (x, y) plt.show ()
At this point, the study on "how to understand the classes and modularity of Python" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 219
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.