I. Object-Oriented
Object-oriented programming (OOP) is a programming paradigm and a programmer.
Law. Objects refer to instances of classes. Classes are templates for creating objects. A class can create many objects, each of which is a class type.
A variable; the process of creating objects is also called instantiation of classes. Programming methods can be divided into two main categories: process-oriented and pair-oriented.
Like, their main difference is:
PROCESS-ORIENTED PROGRAMMING: With instructions as the core and around what is happening, the program has a series of linear steps. The main idea is that code acts on data. Face-to-face object programming (OOP): With data as the core, the program is compiled around "who will influence", the program is organized around data and interfaces strictly defined for data, and the direction of code is controlled by data. |
The main concepts of object-oriented programming are as follows:
Class: Defines the structure and behavior (data and code) shared by multiple objects of the same type. Object: An instance of a class. It contains both data (variables, also known as attributes) and code (functions, also known as methods). Encapsulation: A programming mechanism that hides implementation details; binds code and processed data together to ensure that programs and data are not interfered with externally and are not misused. |
II. Class Creation
Create classes using class keywords
A superclass is a collection class body of one or more parent classes for inheritance, which can include: declarative statements, class member definitions, data attributes, and methods.
Class ClassName(bases): #If there is no inheritance relationship, bases may not be provided 'class documentation string' #Class documents are optional Data = value #Define data attributes def method(self , ...) #Define method attributes self.member = value class MyClass(): """A simple example class""" i = 12345 def f(self): return 'hello world'
Class methods and calls
Instances (objects) usually contain attributes and methods.
Data attributes: that is, variable callable method: object.method(), that is, function
In OOP, an instance is like a record with "data", while a class is a "program" that handles these records. Calling method phases through instances
When the method of the class to which it belongs is invoked to process the current instance, it automatically changes to class.method(instance), similar to obj.method(arg...).
So each method in the class must have a self parameter, which implies the current instance; within the method, do the self attribute
Assignment operations produce properties for each instance; methods are not allowed to be invoked without instances.
In [1]: class MyClass(): ...: """A simple example class""" ...: i = 12345 ...: def f(self): ...: return 'hello world' ...: In [2]: x=MyClass() #Instantiate a class In [3]: x.f() #Calling methods of classes Out[3]: 'hello world' In [4]: x.i Out[4]: 12345 In [5]: x.i=23456 #Modify member variables In [6]: x.i Out[6]: 23456
Constructors and Destructor
Constructor: When creating an instance, python automatically calls the _init_ method in the class to provide attributes for the instance implicitly
_ The init_ method is called a constructor, and if the _init_ method is not defined in the class, the instance is created initially as a simple namespace. The constructor cannot have a return value.
In [8]: class Myclass(object): ...: message='Hello,Developer' ...: def show(self): ...: print(self.message) ...: In [9]: class Myclass(object): ...: message='Hello,Developer' ...: def show(self): ...: print(self.message) ...: def __init__(self): #Constructor ...: print('Constructor is called') ...: In [10]: inst=Myclass() #When the Myclass class class is instantiated, the constructor is automatically executed Constructor is called In [11]: inst.show() Hello,Developer
Destructors: _del_ methods are called destructors and are called when objects are destroyed (released). Destructors are often used
Do "clean up" work, such as database link objects can release the occupation of database resources in the destructor.
In [17]: class Myclass1(object): ...: message='Hello,Developer' ...: def show(self): ...: print(self.message) ...: def __init__(self): ...: print('Constructor is called') ...: def __del__(self): ...: print('Destructor is called!') ...: In [18]: inst1=Myclass1() #instantiate Constructor is called In [19]: inst1.show() Hello,Developer In [20]: del inst1 #Destructive function Destructor is called!
Special attributes of classes: You can use the _dict_ dictionary attributes of classes or built-in dir() functions to get attributes of classes.
In [27]: dir(Myclass1) #View properties and methods owned by classes Out[27]: ['__class__', '__del__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'message', 'show']
Instance attributes (member variables)
Instances only have data attributes (methods are class attributes) and usually provide attributes for instances through constructors "_init_"; these data attributes
Sex is independent of other instances or classes; when an instance is released, its attributes will also be cleared. Built-in function dir() or special attributes of instances
_ dict_ can be used to view instance properties.
In [31]: class Myclass2(object): ...: message='Hello,Developer' #Class member attributes ...: def show(self): ...: print(self.message) #Instance member variables ...: print('Here is %s in %s' %(self.name,self.color)) ...: def __init__(self,name='unset',color='black'): ...: print('Constructor is called with parms:',name,'',color) ...: self.name=name ...: self.color=color ...: In [32]: Myclass2.message #Output class variable Out[32]: 'Hello,Developer' In [33]: Myclass2.message='Hello Python' #Changing class member variables In [34]: Myclass2.message Out[34]: 'Hello Python' In [35]: init3=Myclass2() #Instance class Myclass2 Constructor is called with parms: unset black In [36]: init3.message #Access class member variables Out[36]: 'Hello Python' In [37]: init3.message='Hello' #Changing class member variables In [39]: Myclass2.message #You can see that instance objects cannot change class member objects Out[39]: 'Hello Python'
Available variables in class methods
Instance variables: specify the name of the variable and refer to the example itself; self. variable name |
Modifiers for class members
Public members, accessible anywhere
Private members, only within a class can approach
class C: classname = 'public variable' #A public field of a class, that is, a variable __classfoo = "private variable" #Class's private fields, with variables declared at the beginning of _ as private variables def __init__(self): self.name = 'public variable' #The public field of an object, that is, a variable self.__foo = "private variable" #Object's private field, with the variable declared at the beginning of _ as the private variable
Static fields (belonging to classes)
Public static variables: classes are accessible; classes are accessible internally; derived classes are accessible
Private static variables: accessible only within a class
Ordinary fields (belonging to objects)
Public Common Variables: Objects can be accessed; Classes can be accessed internally; Derived classes can be accessed
Private common variables: accessible only within a class
In [42]: class Myclass2(object): ...: message='Hello,Developer' #Class Membership ...: __classname='Python' ...: def show(self): ...: print(self.message) ...: print('Here is %s in %s' %(self.name,self.color)) ...: def __init__(self,name='unset',color='black'): ...: print('Constructor is called with parms:',name,'',color) ...: self.name=name ...: self.__color=color In [43]: inst4=Myclass2() #instantiate Constructor is called with parms: unset black In [44]: inst4.message #Instantiated objects can access public variables of classes Out[44]: 'Hello,Developer' In [45]: inst4.__classname #Instantiated objects cannot access private variables of classes -------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-45-379f39c829cf> in <module>() ----> 1 inst4.__classname In [47]: inst4.name #Instance objects can access object public variables Out[47]: 'unset' In [48]: inst4.__color #Instance objects cannot access object private variables externally -------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-48-5db61d225aac> in <module>() ----> 1 inst4.__color AttributeError: 'Myclass2' object has no attribute '__color'
o. Static and class functions
Python supports two functions that access members based on class names: static functions and class functions. The difference between them is that class functions have an implicit meaning.
The sex parameter cls can be used to obtain information, but the static function does not have this parameter. Static functions are defined using the decorator @static method, and classes
The function is defined using the decorator @classmethod.
class Myclass(object): message='Hello,Developer' def show(self): print('self.message') print('Here is %s in %s !' %(self.name,self.color)) @staticmethod #Define static functions to access class member variables def printMessage(): print('print Message is called ') print(Myclass.message) @classmethod #Define class functions, the first parameter must be cls def creatobj(cls,name,color): print('Object will be created: %s(%s,%s)' %(cls.__name__,name,color)) return cls(name,color) def __init__(self,name='unset',color='black'): print('Constructor is called with params:',name,'',color) self.anme=name self.color=color def __def__(self): print('Destructor is called for %s' %self.name) Myclass.printMessage() #Direct calls to static functions inst=Myclass.creatobj('Toby', 'Red') print(inst.message) //Output results: print Message is called #Static function output Hello,Developer Object will be created: Myclass(Toby,Red) #Class function output Constructor is called with params: Toby Red #Constructor Hello,Developer #print output
Inheritance and Polymorphism
Inheritance between classes is an important method of object-oriented design, which can simplify code and optimize design patterns.
Python classes can specify base classes in parentheses when they are defined. All Pyhon classes are subclasses of object type.
class BaseClass(object) #Parent Class Definition block_class class SubClass(BaseClass) #Subclass Definition block_class
New Classes and Classical Classes
There are two kinds of classes in Python, classical class and new class. The difference between them is:
1) Different ways of writing class A: #Classical Classes pass class B(object): #new-style class pass The default in Python 2.x is classic classes, and only the explicit inheritance of object is the new class. Python 3.x defaults to new classes, without explicit inheritance of object s 2) In multi-inheritance, the search order of inheritance search has changed. The search order of multi-inheritance attributes of classical classes: first, go deep to the left of the inheritance tree, and then to the left of the inheritance tree. Return and start looking for the right; New class multi-inheritance attribute search order: first horizontal search, then move up 3) The new class is more in line with OOP programming idea and unifies the type mechanism in python. New class objects can obtain their own types directly through the _class__attribute:type The new class adds _slots_ built-in attributes, which can lock the type of instance attributes into the range specified by _slots__ New class adds _getattribute__method |
class BaseA(object): def move(self): print('move called in BaseA') class BaseB(object): def move(self): print('move called in BaseB') class BaseC(BaseA): def move(self): print('move called in BaseC') class Sub(BaseC,BaseB): def move(self): print('move called in Sub') inst=Sub() inst.move()
In the multiple inheritance of this new class, when the subclass inherits multiple parent classes and calls common methods, the Python interpreter selects the nearest base class member method. The above example move() search order is Sub, BaseC, BaseA, BaseB.
Built-in functions for classes and instances
issubclass() | Boolean function, which determines whether a class is derived from another class. issubclass(sub,sup) |
isinstance() | Boolean function, which determines whether an object is an instance of a given class. isinstance(obj1,class_obj2) |
hasattr() | Boolean function, to determine whether an object has a specified property, hasattr(obj,'attr') Similar functions include getattr(), setattr(), and delattr(). |
super() | Find its parent class in the subclass to call its attributes; in general, only the ancestor method can be invoked in a non-binding manner; super() can be used to pass in instances or type objects, super(type[,obj]) |
In [1]: class Person(): ...: def __init__(self,name): ...: self.name=name ...: In [2]: class EmailPerson(Person): ...: def __init__(self,name,email): ...: super.__init__(name) ...: self.email=email
In the example above, the subclass EmailPerson obtains the definition of the parent Person through the super() method, and the _init_() of the subclass is called.
Person. _init_() method. It automatically passes the self parameter to the parent class. This not only inherits the definition method in the parent class, but also
You can create attributes unique to subclasses.
Operator overloading
Intercept built-in operations in methods -- When an instance of a class appears in the built-in function, Python automatically calls a custom method, and
And return the operation result of the custom method. Operator overloading lets classes intercept regular Pyhton operations: classes can overload all expressions
Operators; Classes can also overload built-in operations such as printing, function calls, attribute point operations; Classes can overload built-in types of behavior items of class instances.
Load is implemented by providing a class method with a special name.
Special Method Development Class
In addition to _init_ and _del_, the Python class supports many special methods, all of which start and end with double underscores. Some special methods have default behavior, but no default behavior is to be implemented when needed. These special methods are python.
Powerful tools for extending classes can be implemented by emulating standard types and special methods for overloading operators that allow classes to pass through overloaded labels
Quasi-operators +,* even include subscripts and mapping operations [] to simulate standard types.
Method | heavy load | call |
__init__ | Constructor | Object creation: x=class(args) |
__del__ | Destructive function | x object object |
__add__ | Operator+ | If there is no _iadd_,x+y, x+=y |
__or__ | Operator: (bit OR) | If there is no _ior_,x|y, x|=y |
__repr__,__str__ | Printing, Conversion | print(x),repr(x),str(x) |
__call__ | function call | x(*args,**kargs) |
__getattr__ | dot operator | x.undefined |
__setattr__ | Attribute assignment statement | x.any=value |
__delattr__ | Attribute deletion | del x.any |
__getattribute__ | Attribute acquisition | x.any |
__getitem__ | Index operation | x[key],x[i:j], for loop without _iter__ |
__setitem__ | Index assignment operation | x[key]=value,x[i:j]=sequence |
__delitem__ | Index and slice deletion | del x[key],del[i:j] |
__len__ | length | len(x), if there is no _bool_ truth test |
__bool__ | Boolean test | bool(x), true test |
__lt,__gt__ | Specific comparisons | x<y,x>y,x<=y,x>=y,x==y,x!=y |
__le__,__ge__ | ||
__eq__,__ne__ | ||
__radd__ | Right additive | other+x |
__iadd__ | Field (enhanced) addition | x+=y |
__iter__,__next__ | Iterative environment | I=iter(x),next(I) |
__contains__ | Membership testing | item in x |
__index__ | Integer value | hex(x),bin(x),oct(x),o[x] |
__enter__,__exit__ | Context Manager | with obj as var: |
__get__,__set__ | Description Operator | x.attr,x.attr=value,del x.attr |
__delete__ | delete | Delete objects after _del__ |
__new__ | Establish | Create objects before _init__ |