This article describes the object-oriented feature of the Python series for automated O & M. For more information, see. Object-oriented programming
Process-oriented: code from top to bottom according to business logic
Function: encapsulate a function code into a function and call it directly later without writing it again.
Object-oriented: classifies and encapsulates functions to make development faster, better, and stronger ..."
# Programming languages such as Java and C # only support object-oriented programming, while Python supports mixed functional programming and object-oriented programming
Object-oriented example
# Functional programming def bar (): print ('bar') bar () # directly call a function # object-oriented programming class Foo: # Create a class def bar (self ): # define a function in the class. here, self is a special parameter. When an object is created, Foo will pass itself in print ('bar') obj = Foo () # create an Object obj. bar () # Remove functions from the handler class by objects
Three main features of object-oriented: encapsulation inheritance polymorphism
Encapsulation
Encapsulate the required content into the created class and call
Class Foo: # Create a class def _ init _ (self, name, age): # Foo will encapsulate the two parameters in its own class after receiving them. name = name self. age = age obj = Foo ('Kobe', 18) # create an object and pass two parameters print (obj. name, obj. age) # output of encapsulated parameters called outside: kobe 18
Class Member
Fields: common fields and static fields
Methods: common methods, static methods, and class methods
Attribute: common attribute
1) field (parameters encapsulated in the class)
Class Foo: # Field (static field stored in class) CC = "China" def _ init _ (self, name ): # fields (common fields are stored in objects) self. name = name # access obj = Foo ('Shanghai') print (obj. name) # access print (Foo. CC)
2) method (functions encapsulated in the class)
Class Foo: def show (self): # normal method: the execution method called by the object belongs to the print (self. name) @ staticmethod def f1 (): # print ('F1 ') @ classmethod def f2 (cls) executed by the class call ): # class is automatically passed to the class name # class method # cls is the class name plus () create object print (cls) # create Object obj = Foo () # access the normal method obj through an object. show () # access the static method Foo through the class. f1 () # The Class method will pass the class Foo name directly to the function Foo. f2 ()
3) attributes
Before defining the attributes of a class, we need to add brackets () after the method name in the methods class: for example, obj. f1 ()
After the attribute is defined, the methods in the classes class can be directly obj. f1
Class Foo: @ property def f1 (self): print ('F1') obj = Foo () obj. f1 # directly access through an object without brackets
Configurable and deleteable
Class Foo: @ property # add the property modifier def f1 (self): print ('F1') @ f1.setter on the class method # set the value def f1 (self, values ): print (values) @ f1.deleter # you can delete def f1 (self): print ('Del... ') obj = Foo () obj. f1 # directly access obj through the object without brackets. f2 = 100del obj. f1 output: f1del...
Another method of writing class attributes
Class Foo: def f1 (self): return 100 def f2 (self, value): print (value) def f3 (self): print ('20140901 ') # class property definition Foo = property (fget = f1, fset = f2, fdel = f3) obj = Foo () # VALUE: ret = obj. fooprint (ret) # assign values to obj. foo = 200 # delete del obj. foo #100200300 output
Class member modifier
Class member modifier: defines fields or methods in the class as public or private
Public Member: accessible anywhere
Private members: they can only be accessed within the class.
Class Foo: _ cc = 123 def _ init _ (self, name): self. _ name = name # Add Two underscores _ to indicate that def f1 (self): print (self. _ name) @ staticmethod # The staticmethod modifier is a static method. you can call def f3 (self): print (Foo. _ cc) obj = Foo ('Kobe') # print (obj. _ name) # failed to access the internal common field through the external Object obj. f1 () # print (Foo. _ cc) # internal static fields cannot be accessed externally. obj. f3 () # special access method print (obj. _ Foo _ name)
Special member of the class
_ Doc _ # class description
_ Module _ # module of the current object
_ Class _ # class of the current object
_ Str _ # value returned when the object is printed
_ Init _ # constructor
_ Del _ # destructor
_ Call _ # trigger execution with brackets after the object
_ Dict _ # all members in a class or object
_ Getitem _ # index operations such as dictionaries
_ Setitem _ # Index operation
_ Delitem _ # Index operation
1) _ doc _ description
Class Foo: "comment _ doc _" obj = Foo () print (obj. _ doc _) output: comment _ doc _ 2) _ module _ and _ class _ from lib. aa import C obj = C () print obj. _ module _ # output lib. aa: print obj of the output module. _ class _ # output lib. aa. c, that is, the output class
3) _ init _ and _ str __
Class Foo: def _ init _ (self, name, age): # constructor self. name = name self. age = age def _ str _ (self): # str method return '% s-% s' % (self. name, self. age) obj1 = Foo (name = 'Kobe', age = 18) obj2 = Foo (name = 'Jordan ', age = 18) print (obj1) print (obj2) # output: kobe-18 jordan-18
4) _ del __
Class Foo: def _ init _ (self, name, age): # constructor self. name = name self. age = age # destructor: Run def _ del _ (self): pass before garbage collection.
5) _ call __
Class Foo: def _ call _ (self, * args, ** kwargs): print ('call') p = Foo () # execute the _ call _ method p () after the object is enclosed in parentheses # A class creates an object and two parentheses are executed. The _ call _ method Foo ()() # output: callcall
6) _ dict __
Class Foo: def _ init _ (self, name, age): # constructor self. name = name self. age = age obj1 = Foo (name = 'Kobe', age = 18) # get the encapsulated data in the object and return a dictionary ret = obj1. _ dict _ print (ret) # output: {'name': 'Kobe', 'age': 18} # All class methods # print (Foo. _ dict __)
6) _ getitem _ setitem _ delitem _ is used for index operations, such as dictionaries. values can be obtained, set, and deleted.
Class Foo: def _ getitem _ (self, item): print ('getitem ') def _ setitem _ (self, key, value ): print ('secret') print (item. start, item. stop, item. step) def _ delitem _ (self, key): print ('delitem') # Automatically execute the getitem method obj = Foo () in the brackets syntax () obj ['AB'] # Use the setitem method obj ['k1 '] = 111del obj ['k1'] # Use the setitem method obj [] # output setitemdelitemgetitem1 6 2
7) _ iter _, _ isinstance _, and _ issubclass __
Class Bar: pass class Foo (Bar): # returns an iteratable object def _ iter _ (self): # return iter ([11, 22, 33, 44]) yield 1 yield 2 obj = Foo () for item in obj: print (item) # check if obj is an instance of Foo ret = isinstance (obj, Foo) # You can also check whether it is an instance of the parent class # ret = isinstance (obj, Bar) print (ret) # check whether Foo is a subclass of Bar ret1 = issubclass (Foo, Bar) print (ret1) # output 12 TrueTrue
Super
Super is used to solve the problem of multiple inheritance in Python and forcibly execute the methods in the parent class.
Class C1: def f1 (self): print ('C1. f1 ') class C2 (C1): def f1 (self): # actively execute the f1 method super (C2, self) of the parent class ). f1 () print ('C2. f1 ') obj = C2 () obj. f1 () # output: c1.f1c2. f1
Using super to add functions without changing the source code
Directory backend-commons. pyindex. pylib. pysetting. py commons. py> class Foo: def f1 (self): print ('foo. f1 ') index. py> from setting import ClassNamefrom setting import Path def execute (): model = _ import _ (Path, fromlist = True) cls = getattr (model, ClassName) obj = cls () obj. f1 () if _ name _ = '_ main _': execute () setting >>#path = "backend. commons "# ClassName = 'foo' Path =" lib "ClassName = 'myfoo' lib> from backend. commons import Foo class MyFoo (Foo): def f1 (self): print ('before') super (MyFoo, self ). when f1 () print ('after') runs the lib we added, the result is as follows: beforeFoo. f1after
Use super to implement ordered Dictionary
Class MyDict (dict): def _ init _ (self): self. li = [] super (MyDict, self ). _ init _ () def _ setitem _ (self, key, value): self. li. append (key) super (MyDict, self ). _ setitem _ (key, value) def _ str _ (self): temp_list = [] for key in self. li: value = self. get (key) temp_list.append ("'% s': % s" % (key, value) temp_str = "{" + ",". join (temp_list) + "}" return temp_str obj = MyDict () obj ['k1 '] = 123obj ['K2'] = 456 print (obj) # output {'k1 ': 123, 'K2': 456}
Singleton mode
# The Singleton mode is a common software design mode. Its core structure only contains a special class called singleton class. The Singleton mode ensures that there is only one instance in a class in the system and the instance is easy to access, so as to conveniently control the number of instances and save system resources. If you want to have only one class object in the system, the singleton mode is the best solution.
Class Foo: instance = None def _ init _ (self, name): self. name = name @ classmethod def get_instance (cls): if cls. instance: return cls. instance else: obj = cls ('Alex ') cls. instance = obj return obj obj1 = Foo. get_instance () obj2 = Foo. get_instance () print (obj1) print (obj2) # output <__main __. foo object at 0x000001C09B130B70> <__ main __. foo object at 0x000001C09B130B70>
Exception handling
while True: num1 = input('num1: ') num2 = input('num2: ') try: num1 = int(num1) num2 = int(num2) ret = num1 + num2 except Exception as ex: print(ex) except ValueError as ex: print(ex) except IndexError as ex: print(ex)
Complete exception handling code
Try: raise Exception ('proactive error... ') passexcept ValueError as ex: print (ex) failed t Exception as ex: print (ex) else: passfinally: pass
The above describes the object-oriented content of the Python series for automated O & M. For more information, see other related articles in the first PHP community!