Python Series 6 object-oriented, python series object-oriented
Directory
- Generator and iterator
- String formatting
- Built-in function vars
- Reflection
- Object-Oriented Programming
I. Generator and iterator
1. Generator
The generator has a generation capability, which only represents a generation capability. When we need to use it, it will be generated through the iterator. Because it only represents this generation capability, the generator saves a lot of memory, and generally uses yield to differentiate the generated location. Use next to locate the next position.
# When you directly execute the genetor function, a 1 will be returned first, and then exit, because yield #2 will be executed after a next operation. then exit # That is, yield is actually an address storage mechanism of the generator. Only through next will the address point to the next yielddef genetor (): print (1) yield 1 print (2) yield 2 print (3) yield 3 print (4) yield 4obj = genetor () a = obj. _ next _ () B = obj. _ next _ () c = obj. _ next _ () d = obj. _ next __()
Write an xrange Function
def xrange(args): value = 0 while True: if value >= args: return else: yield value value += 1for i in xrange(5): print(i)
2. iterator
The iterator represents this access capability. It can iterate the object generated by the generator through next again and again. Therefore, it can get the data we want. A for Loop is an iterator. The above code can be used to iterate the generator through the for loop.
Ii. String formatting
1. String formatting
String formatting is more effective than Splicing
String formatting is more convenient
2.% format
# % Usage format. The content in [] can be omitted % [(name)] [flags] [width]. [precision] typecode
[(Name)]
Format: % [(name)] [flags] [width]. [precision] typecode (name): Optional. It is used to select the specified key flags: whether the input format is left-aligned or right-aligned. It is used with width and + right-aligned, + is added before a positive number, and---Is added before a negative number, that is, the left alignment space is unchanged, that is, the right alignment is 0, and the front is filled with 0 width (optional), which occupies the width. number of digits reserved after the precision decimal point typecode s string f precision number d integer
Example:
String
S1 = "I am % + 10d, age %-10d, % 10d % 010d" % (10, 10, 10, 10) s2 = "I am % + 10d, age %-10d, % 10d % 010d "% (-10,-10,-10,-10) print (s1) print (s2) Result: I am + 10, age 10, 10 bytes running 10i am-10, age-10,-10-000000010
Integer
# Common examples: s1 = "I am % s" % "hu" s2 = "I am % (name) s, age % (age) s" % {"name ": "hu", "age": 13} s3 = "3.335 + 4.2345 = % 2.f" % 7.23566 print (s1, s2, s3)
3. Common format formatting Methods
[[Fill] align] [sign] [#] [0] [width] [,] [. precision] [type] is in the format of format. Many of them are the same as %. Below we will only list common usage of this parameter.
s1 = "i am {}, {}, {}".format("hu", "zhou", "12")s1 = "I am {}, {}, {}".format(*["hu", "zhou", "12"])s1 = "I am {0}, {1}, {0}".format("seven", 18)s1 = "I am {0}, {1}, {0}".format(*["seven", 19])s1 = "I am {name}, {age}, {name}".format(name="hu", age=11)s1 = "I am {name}, {age}, {name}".format(**{"name":"hu", "age":11})s1 = "I am {:s}, {:d}, {:f}".format("hu", 18, 1823.923)s1 = "{:b},{:x},{:o}".format(10,10,10)s1 = "{:#b},{:#x},{:#o}".format(10,10,10)
Iii. built-in function vars
# Default variables of built-in functions
Print (vars ())
{'_ File _': 'C:/Users/zhou/PycharmProjects/fullstack2/6_20/test. py', '_ doc _': None, '_ cached _': None, '_ builtins __': <module 'builtins '(built-in)>,' _ spec _ ': None,' _ package _ ': None,' _ name __': '_ main _', '_ loader _': <_ frozen_importlib_external.SourceFileLoader object at 0x00000063B24C4F98>}
1. _ file _ absolute path of the current Working Environment
2. If _ name _ is in the current working directory, _ main __is returned. If it is an imported module, the returned Module name is
3. _ packge __
4. The Variable _ doc _ stores the description of the file, that is, the description of the file function at the beginning of the file.
5. _ cached _ this is the cache. If it is an imported module, there will be a cache.
6. _ builtins _ this is a built-in function.
'''This is a test document named test''' import indexprint (index. _ name _) print (_ file _) print (_ doc _) print (index. _ cached _): index _ main _ C:/Users/zhou/PycharmProjects/fullstack2/6_20/test. py is a document named testC: \ Users \ zhou \ PycharmProjects \ fullstack2 \ 6_20 \__ pycache __\ index. cpython-35.pyc
Iv. Reflection
1. Definition of reflection
Reflection is to operate its members in an object in the form of a string.
2. Differences between the _ import _ method and the import Method
<1>. _ import _ you can use the string import module.
<2>. import cannot use strings to import modules.
Simple import and _ import __
# S3 is the name of a function # An error is reported for direct import of strings. # Use _ import _ for import, it is equivalent to import s3 # import "s3" module = _ import _ ("s3") module. f3 ()
Extended _ import __. when we need to import a hierarchical module, we need to use the fromlist Parameter
# There is a module order in the lib directory. to import it, you need to use the following method module = _ import _ ("lib. order ", fromlist = True) print (module. add_order ())
3. Reflection Method
<1>. hasattr (module, keyword) determines whether the keyword is in the module. If it is in the module, true is returned. If it is not in the module, false is returned.
<2>. getattr (module, keyword): If the keyword is a function, return the function. If it is a variable, return the variable (all the keywords in it are passed as strings. If it is a function, the string cannot be used by default. This function can be used to convert it into a function)
<3>. setattr (module, keyword, value) adds a keyword to the module. It can be a variable or a function. Addition and deletion are completed in the memory and will not affect the file content.
<4>. delattr (module, keyword) deletes the keyword from the module.
S3 content def f1 (): print ("f1 ") ==============================## import s3, judge whether the keyword is imported s3ret1 = hasattr (s3, "f1") ret2 = hasattr (s3, "f11") print (ret1) print (ret2) in s3. Result: TrueFalseHasattr ()
# Import module, get the function in the module through the string # then execute the function # string f1 can not be executed, only get the function through getattr in the execution of import s3func = getattr (s3, 'f1 ') func ()
Getattr ()
# Setattr transmits a key-value pair, while hasattr judges only the key, not the value. # because the "name" is not found at the beginning, false is returned, this key is set through setattr, so the returned result is Trueimport s3print (hasattr (s3, "name") setattr (s3, "name", "hu") print (hasattr (s3, "name") Result: FalseTrue
Setattr ()
# F1 exists at the beginning, so True is returned. # After del is deleted, the returned value is False. import s3print (hasattr (s3, "f1") delattr (s3, "f1") print (hasattr (s3, "f1") Result: TrueFalse
Delattr ()
Url = input ("Enter url:") target_module, target_func = url. split ("/") print (target_func, target_module) module = _ import _ ("lib. "+ target_module, fromlist = True) print (module) if hasattr (module, target_func): # module.tar get_func () target_func = getattr (module, target_func) target_func () else: print ("404 ")Python instance (web framework-based routing system)
V. Object-Oriented Programming
1. Programming
In our daily life, there are many programming methods, such as process-oriented, object-oriented, or functional programming. Their differences are quite large, but the ultimate goal is only one, that is to simplify the workload. It's like building a house. The process is that I want to buy bricks to buy tiles and build them on my own. Functional programming is that I buy bricks to buy tiles and then ask the carpenter to do it for me, the object-oriented approach is that I want to buy a house directly and save my work.
2. Object-Oriented Programming
(1). Definition class
What is a class? A class is a cohesive package composed of a specific metadata. It is composed of multiple functions to complete a combination of functions. Now that we have functions, why do we need classes? When our functions have a large number of Identical parameters or functions, classes are needed to simplify their operations.
# The keyword class creates a class. The class name Foo # defines three methods. The self in the __init _ f1 and f2 # methods is the default parameter and must contain class Foo: def _ init _ (self): self. name = "hu" def f1 (self): print ("f1") def f2 (self): print ("f1 ")
(2). Execution class (create object)
What is an object? In Python, everything is an object. After we create a type of data, it is only a type of data, and the methods and parameters are all extensive, we need an object to instantiate it. That is to say, when we say: This is a person. You certainly don't know who he is, because he only represents a type of data. When we say that he is Li Gang, you will suddenly realize that he is Li Gang, this is because our class is instantiated.
The _ init _ method is used to create objects and encapsulate content.
The self variable in each method is added by default in Python to pass objects. When an obj object is created, the _ init _ method in the class is automatically called, and obj is passed to self as a parameter.
# Create an object using the class name and brackets, and call the method class Foo: def _ init _ (self): self. name = "hu" def f1 (self): print ("f1") def f2 (self): print ("f1") obj = Foo () obj. f1 ()
Graph of the created object: all objects are in the memory. when an object is created, the _ init _ method in the class is executed by default, and the object on the right is generated through the init method.
(3). Three major features
Object-oriented languages generally have the following three features: encapsulation, inheritance, and polymorphism. It is precisely because of this that a large object-oriented system is formed, so that you can express everything through it. Ever-changing.
<1>. Encapsulation
Encapsulation is to encapsulate a series of identical functions into objects to simplify the class method. Before introducing encapsulation, let's first compare the differences between encapsulation and non-encapsulation.
We can see from the example below that encapsulation is to define some repeated quantities in one place and then use them.
# Data class Person: def chifan (self, name, age, gender): print (name, "dinner") def shuijiao (self, name, age, gender) is not encapsulated ): print (name, "Sleep") def dadoudou (self, name, age, gender): print (name, "doubebean ")
No Encapsulation
Class Person: def _ init _ (self, name, age, gender): self. name = name self. age = age self. gender = gender def chifan (self): print (self. name, "dinner") def shujiao (self): print (self. name, "Sleep") def dadoudou (self): print (self. name, "Doudou ")
Encapsulation
Use Cases:
A. When a method of the same type has multiple templates, it can be directly encapsulated into an object.
B. Use classes as templates to create multiple objects (the number of encapsulated objects is different)
For example, a Person class is defined, and three parameters are encapsulated with _ init _ for the following two methods to be called and archived through the pickle module.
import pickleclass Person: def __init__(self, name, age, weight): self.Name = name self.Age = age self.Weight = weight def chi(self): self.Weight += 2 def jianshen(self): self.Weight -= 1ret = pickle.load(open('youxi', 'rb'))if ret: print(ret.Weight) obj1 = Person(ret.Name, ret.Age, ret.Weight)else: obj1 = Person('xiaoming', 12, 200) obj1.chi() obj1.chi() obj1.chi() obj1.jianshen()pickle.dump(obj1, open('youxi', 'wb'))
<2>. Inheritance
We have heard of the parent-child business. In fact, inheritance means this. When we define several classes, we find that these classes have some common attributes and methods, at this time, we can define these common attributes and methods into a class as the father of these classes, then these classes can inherit the attributes and methods of the father as their own methods. In the following example, three classes are defined: one parent class, one son, one daughter. The parent class methods include eating and drinking, and the son method is ticket, the daughter's method is gambling. When the son inherits the father, he will inherit the father's method. Naturally, he will eat and drink, and his daughter will also.
Class Parent: def chi (self): print ("eat") def he (self): print ("drink") class son (Parent): def piao (self ): print ("pass") class nver (Parent): def du (self): print ("bet") obj = son () obj. chi () obj. he () obj. piao () obj1 = nver () obj1.chi () obj1.he () obj1.du ()View Code
Inherited rules
1. Subclass inherits all methods of the parent class by default.
2. If the subclass has the same method as the parent class, the subclass method will be used first.
3. Python can inherit multiple classes (this is a feature of Python, which is not available in C # and java)
Sequence rules that inherit multiple classes in Python
Because Python can inherit more than one class, when a child inherits the parent class, its rule is generally executed first on the left and then on the right. When there is nesting, return to the subclass to perform recursive search every time. Example
For example, if the methods in the subclass do not exist, they are searched up sequentially.
# Several classes are created. For example, in the inheritance relationship, A class A: def f1 (self): print ("A") class B: def f1 (self ): print ("B") class C (A): def f1 (self): print ("C") class D (B): def f1 (self ): print ("D") class E (C, D): def f1 (self): print ("E") obj = E () obj. f1 ()I
class Hu: def f1(self): print("Hu")class A(Hu): def f1(self): print("A")class B(Hu): def f1(self): print("B")class C(A): def f1(self): print("C")class D(B): def f1(self): print("D")class E(C, D): def f1(self): print("E")obj = E()obj.f1()II
<3>. Polymorphism
Because there is no type constraint when passing parameters in Python, It is a polymorphism and we can transfer any data.
(4). Member
Method: static method (no need to use the content encapsulated by the object @ staticmethod, directly called by class), common method (using the object for encapsulation), Class Method
Field: static field (each object has one copy), common field (encapsulated in the object)
Feature: only one method can be forged into a field.
Method of Calling members:
1. If there is no self, use the class for calling.
2. If self exists, it is called with an object.
3. Exception Handling
Some unknown errors may occur during program execution, but we always want to return these errors to the user in a controllable manner. This means exception handling is used.
Exception Handling Format:
# When an error occurs in the statement after try, the subsequent statement will be triggered and a controllable error message a = input ("input number:") try: a = int (a) failed t Exception as e: print ("error .... ")