Show limited interfaces to external
When you publish a Python third-party package, you do not want all the functions or classes in the code to be externally import, add the all property to the init.py, and fill in the list with the Import class or function name, which can act as a restricted import. Prevent external import of other functions or classes.
#!/usr/bin/env python#-*-coding:utf-8-*-from Base Import apibasefrom Client import clientfrom decorator import Interfa CE, export, streamfrom server import serverfrom storage import storagefrom util import (Logformatter, disable_logging_to_s Tderr, enable_logging_to_kids, info) all = [' apibase ', ' Client ', ' logformatter ', ' Server ', ' Storage ', ' Disable ' _logging_to_stderr ', ' enable_logging_to_kids ', ' export ', ' info ', ' interface ', ' stream ']
With the Magic
The WITH statement requires an object that supports the context management protocol, and the Context Management protocol contains the Enter and exit two methods. The WITH statement establishes a run-time context that requires both methods to perform entry and exit operations.
Where the context expression is the expression that follows with, and the expression returns a context-management object.
# Common with use scenario with open ("Test.txt", "R") as My_file: # Note that the return value of the Enter () method is assigned to My_file, for line in My_file: Print Line
Detailed principles can be viewed in this article, talking about Python with statements.
Knowing the specific principles, we can customize the classes that support the context Management protocol, implementing the Enter and exit methods in the class.
#!/usr/bin/env python#-*-coding:utf-8-*-class Mywith (object): def init (self): print "Init method" def Enter (self): print ' Enter method ' return self # return object to as after variable def exit (self, exc_type, Exc_value, exc_ Traceback): print "Exit method" if Exc_traceback is None: print "Exited without Exception" return True Else: print "Exited with Exception" return falsedef Test_with (): With Mywith () as My_with: Print "Running My_with" print "------Split line-----" with mywith () as My_with: print "Running before Exception " raise Exception print" Running after Exception "if name = = ' main ': Test_with ()
The results of the implementation are as follows:
Init methodenter methodrunning my_withexit methodexited without Exception------Split Line-----init methodenter methodrunning Before Exceptionexit methodexited with Exceptiontraceback (most recent call last): File "Bin/python", line-in < module> exec (Compile (filef.read (), file, "exec")) file "test_with.py", line <module> test _with () File "test_with.py", line page, in Test_with raise Exceptionexception
It proves that the Enter method is executed first, then the logic inside with is called, and the exit is executed at the end, and exits gracefully even if an exception occurs.
Usage of filter
In contrast to filter, map and reduce use more frequently, and filter, as its name, filters out some elements according to a certain rule.
#!/usr/bin/env python#-*-Coding:utf-8-*-lst = [1, 2, 3, 4, 5, 6]# all odd numbers return true, and even numbers return false to be filtered out of the print filter (lambda x:x % 2 = 0, LST) #输出结果 [1, 3, 5]
A row for judgment
When the condition is satisfied, returns the variable following the equal sign, otherwise returns the Else post statement.
LST = [1, 2, 3]new_lst = lst[0] If LST is not None else noneprint new_lst# Print result 1
A single example of a decorator
Using adorners to implement simple singleton patterns
# single Decorator Def Singleton (CLS): instances = Dict () # initial NULL def _singleton (*args, **kwargs): If CLS not in Insta NCEs: #如果不存在, create and put into dictionary instances[cls] = CLS (*args, **kwargs) return Instances[cls] return _ Singleton@singletonclass Test (object): passif name = = ' main ': t1 = Test () t2 = Test () # both have the same address C13/>print T1, T2
Staticmethod Decorator
Two commonly used decorations in a class, first distinguishing them:
-
Ordinary member function, where the first implicit argument is an object
-
Classmethod Adorner , class method (which gives a feeling very similar to the class method in OC), where the first implicit argument is the class
-
Staticmethod Adorner , without any implicit arguments. static methods in Python are similar to static methods in C + +
#!/usr/bin/env python#-*-coding:utf-8-*-class A (object): # Normal member function def foo (self, x): print "Executing foo ( %s,%s) "% (self, x) @classmethod # Decorate with Classmethod def class_foo (CLS, x): print" Executing Class_foo (%s,%s) "% (CLS, x) @staticmethod # Decorate with Staticmethod def static_foo (x): print" Executing static_ Foo (%s) "% Xdef Test_three_method (): obj = A () # Call the member method of the pop-up directly Obj.foo (" Para ") # here the Obj object as an implicit parameter of the member function is the self obj.class_foo ("Para") # where the class is passed in as an implicit parameter, which is the CLS a.class_foo ("para") #更直接的类方法调用 Obj.static_foo ("Para") # static method does not have any implicit arguments, but it is called through an object or class A.static_foo ("para") if name = = ' main ': test_ Three_method () # function output executing foo (<main. A object at 0x100ba4e10>, para) executing class_foo (<class ' main. A ';, para) executing class_foo (<class ' main. A ';, para) executing static_foo (para) executing Static_foo (para)
Property Decorator
Combine property with adorners to implement properties privatization (simpler and safer implementations of get and set methods ).
#python内建函数property (Fget=none, Fset=none, Fdel=none, Doc=none)
Fget is a function that gets the value of a property, Fset is the function that sets the value of the property, Fdel is the function that deletes the property, and Doc is a string (like a comment). From the implementation point of view, these parameters are optional.
The property has three method getter (), setter (), and delete () to specify Fget, Fset, and Fdel. This represents the following line:
Class Student (object): @property #相当于property. Getter (Score) or property (score) def score (self): return Self._score @score. Setter #相当于score = Property.setter (score) def score (self, value): if not Isinstance (value, int): raise ValueError (' score must is an integer! ') If value < 0 or value >: raise ValueError (' score must between 0 ~ 100! ') Self._score = value
ITER Magic
Through the combination of yield and ITER, we can turn an object into an iterative
With the rewrite of STR, the object can be printed directly from the desired form
#!/usr/bin/env python#-*-coding:utf-8-*-class testiter (object): def init (self): self.lst = [1, 2, 3, 4, 5]
def Read (self): for ele in Xrange (Len (self.lst)): yield ele def iter (self): return Self.read () def str (self): return ', '. Join (Map (str, self.lst)) repr = Strdef test_iter (): obj = Testiter () for Num in obj: print num print objif name = = ' main ': test_iter ()
Magical partial
The partial use is much like a C + + functor (function object).
In StackOverflow, a similar and partial operation is given:
def partial (func, *part_args): def wrapper (*extra_args): args = List (Part_args) args.extend (Extra_ args) return func (*args) return wrapper
Using the attribute bindings of closures to pre-bind some function parameters, return a callable variable until the real call executes:
#!/usr/bin/env python#-*-coding:utf-8-*-from functools import partialdef sum (A, B): return a + bdef test_partial () : Fun = partial (sum, 2) # bind a parameter beforehand, fun becomes a callable variable that requires only one parameter print fun (3) # The implementation is sum (2, 3) if name = = ' main ' : test_partial () # Execution Result 5
Mystery eval
Eval I understand that an inline Python interpreter (which may be biased) interprets the string as the corresponding code and executes it, returning the execution result.
Take a look at the following example:
#!/usr/bin/env python#-*-coding:utf-8-*-def test_first (): return 3def test_second (num): return numaction = { c2/># can be seen as a sandbox "para": 5, "Test_first": Test_first, "Test_second": Test_second}def Test_eavl (): condition = "Para = = 5 and Test_second (Test_first) > 5" res = eval (condition, action) # explains condition and according to a Ction corresponding action execution print resif name = = ' _
Exec
exec ignores the return value in Python, always returns none, and Eval returns the return value of the execution code or statement
EXEC and Eval have the same behavior in addition to the return value when executing code
When the string is passed in, the bytecode is compiled using compile (source, ' <string> ', mode). mode is evaluated as exec and eval
#!/usr/bin/env python#-*-coding:utf-8-*-def test_first (): print "Hello" def test_second (): Test_first () print "Second" Def Test_third (): print "third" action = { "Test_second": Test_second, "Test_third": Test_third }def test_exec (): exec "Test_second" in actionif name = = ' main ': test_exec () # Unable to see execution results
GetAttr
GetAttr (object, name[, default]) returns the named property of the object, and the property name must be a string. If the string is one of the object's property names, the result is the value of the property. For example, GetAttr (x, ' Foobar ') is equivalent to X.foobar. If the property name does not exist, the default value is returned if there is a default value, otherwise the attributeerror is triggered.
# Using Example Class Testgetattr (object): test = "Test Attribute" def say (self): print "test method" Def test_getattr (): my_test = testgetattr () try: print getattr (my_test, "test") except Attributeerror: print " Attribute error! " Try: getattr (My_test, "Say") () except attributeerror: # Without this property, and without specifying a return value, print "Method error!" If name = = ' main ': test_getattr () # Output result Test Attributetest method
Command line Processing
def process_command_line (argv): "" "Return A 2-tuple: (Settings object, args list). ' argv ' is a list of the arguments, or ' None ' for ' sys.argv[1:] '. "" "if argv is NONE:ARGV = sys.argv[1:] # Initialize the parser Object:parser = Optparse. Optionparser (Formatter=optparse. Titledhelpformatter (width=78), Add_help_option=none) # define Options here:parser.add_option (# Customi Zed description; Put--help last '-h ', '--help ', action= ' help ', help= ' Show this help message and exit. ') settings, args = Parser.parse_args (argv) # Check number of arguments, verify values, etc.: if Args:parser.er Ror (' program takes no command-line arguments; ' "%s" ignored. '% (args,)) # Further process settings & args If necessary return settings, Argsdef Main (Argv=none): settings, args = Process_command_line (argv) # application code here, like: # Run (settin GS, args) return 0 # SuccessIf name = = ' main ': status = Main () sys.exit (status)
Read/write CSV file
# read files from CSV, basic and traditional file reads like import Csvwith open (' data.csv ', ' RB ') as f: reader = Csv.reader (f) for row in reader: Print row# writes to the CSV file import Csvwith open (' Data.csv ', ' WB ') as F: writer = Csv.writer (f) writer.writerow ([' Name ', ' Address ', ' age ']) # single-line write data = [ (' xiaoming ', ' China ', ' ten '), (' Lily ', ' USA ', ' a ')] Writer.writerows (data) # Multi-line Write
Various time-form conversions
Just send a picture on the net, then check the document, this is not remember
String formatting
A very useful, many people do not know the features:
>>> name = "Andrew" >>> "My name is {name}". Format (name=name) ' My name is Andrew '