Class concepts
python fully supports procedural programming and object-oriented programming. Object-oriented programming is a design idea, which means that we use objects as the basic unit of the program, and each object contains its own properties and methods. Object-oriented programming has the following main features:
- Encapsulation: Hide the working details of an object from the outside world.
- Inheritance: Inheritance allows subclasses to have properties and methods of the parent class without having to write the same code.
- Polymorphism: Provides a unified interface for entities of different data types.
Syntax for class creation:
class className(base_classes): suite
There are two steps to creating an object:
- Construct Object
- Initialize Object
How to create a class
class Chair(object): def __init__(self, name, legs=4): self.name = name self.legs = legs
_u Init_u Is a special method in Python that initializes objects. It is the first function to be called when an instance is created, and each time an instance is created, its u Init_u Will be called, and its first parameter will always be self, pointing to the instance itself created. (init is the abbreviation of initial, which, as the name implies, is used for initialization)
chair1 = Chair('Barcelona') chair2 = Chair('Bar',1) print(chair2.name) chair1.legs = 2 print(chair1.legs)
Output: Bar 2
Since these attributes are public, they can be read and assigned by the'. 'operator.
Methods and special methods
class Rectangle(object): def __init__(self, width, height): self.width = width self.height = height def area(self): return self.width * self.height rect = Rectangle(5, 4) print(rect.width, rect.height, rect.area())
Output: 5 4 20
The mechanism of python methods, including special methods, is exactly the same as that of functions, with the addition of the first parameter self, the ability to access the properties of self, and the method to call self.
Static data, static methods, and decorators
In some cases, it may be useful to have some data that can be used with classes instead of instances of classes.
class Balloon(object): unique_colors = set() def __init__(self,color): self.color = color Balloon.unique_colors.add(color) @staticmethod def uniqueColorCount(): return len(Balloon.unique_colors) @staticmethod def uniqueColors(): return Balloon.unique_colors.copy()
Static data is created inside a class block but outside any def statement. To access static data, you must give it a name, and the easiest way is to use the class name, as you do in the static method of the Balloon class.
@staticmethod is an ornament. The so-called decorator is a function that takes a function as a parameter, encapsulates the function in a certain way, and then assigns the encapsulated function back to the name of the initial function. So it works the same as the following code;
def uniqueColors(): return Balloon.unique_colors.copy() uniqueColors = staticmethod(uniqueColors)
The symbol @is used to indicate that this is an ornament. The staticmethod() function is a python built-in function.
Inheritance and Polymorphism
inherit
In object-oriented programming, when we have created a class and want to create another similar class, such as adding several methods or modifying the original method, we don't have to start from scratch. We can derive a new class from the original class. We call the original class the parent class or the base class, and the derived class the subclass. The subclass inherits all the data and methods of the parent class.
Start with a simple class;
class Person: def __init__(self, name, job=None, pay=0): self.name = name self.job = job self.pay = pay def lastName(self): return self.name.split()[-1] def giveRaise(self,percent): self.pay = int(self.pay * (1+percent)) def __repr__(self): return '[Person: %s, %s]' %(self.name, self.pay) class Manger(Person): def giveRaise(self, percent, bonus=.10): Person.giveRaise(self, percent + bonus) def side_remark(self): print(self.job, 'A thousand miles trip,Start at foot.') if __name__ == '__main__': bob = Person('Bob Smitch') sue = Person('Sue Jones', job='dev', pay=100000) print(bob) print(sue) print(bob.lastName(),sue.lastName()) sue.giveRaise(.10) print(sue) print('--------Separate-------') tom = Manger('Tom Jones','mgr',50000) tom.giveRaise(.10) tom.side_remark() print(tom.lastName()) print(tom)
Output: [Person: Bob Smitch, 0] [Person: Sue Jones, 100000] Smitch Jones [Person: Sue Jones, 110000] --------Separate------- mgr A thousand miles trip,Start at foot. Jones [Person: Tom Jones, 60000]
polymorphic
if __name__ == '__main__': ... print('----three all----') for obj in (bob, sue, tom): obj.giveRaise(.10) print(obj)
Output: ----three all---- [Person: Bob Smitch, 0] [Person: Sue Jones, 121000] [Person: Tom Jones, 72000]
Here obj may be a Person or a Manger, which is python's polymorphic concept, and the specific behavior of giveRaise depends on which object you use it.
The concept of polymorphism is not difficult to understand. It refers to the same operation on different types of parameters and different behaviors depending on the object (or class) type. Inheritance takes all the data and methods of the parent class, and subclasses can override the methods of the parent class, or add their own unique methods. Inheritance enables polymorphism, which enables unified interfaces for entities of different data types.
Module calls and multi-file applications
Object-oriented programming allows encapsulation of functionality, such as encapsulation methods and data properties, such as into classes. The python module allows you to encapsulate at a higher level which imported functionality - for example, the entire class set, or all instance variables. A module can be thought of as a file with a'.py'suffix. Modules may contain code to execute when importing, but more often, they only provide functions and instantiated classes when importing.
from person import Person bob = Person('Bob Smitch') sue = Person('Sue Jones', job='dev', pay=100000) print(bob) print(sue) print(bob.lastName(),sue.lastName()) sue.giveRaise(.10) print(sue)
The person.py file holds the two defined classes;
from person import Manger tom = Manger('Tom Jones','mgr',50000) tom.giveRaise(.10) tom.side_remark() print(tom.lastName()) print(tom)
Python Standard Library
Python has its own standard libraries, which were installed by default when we downloaded Python, and there are many out-of-the-box modules for us to call on (you can refer to the standard libraries yourself).