Python Object-oriented Advanced (ii)

Source: Internet
Author: User
Tags set set wrapper

1. Garbage collection
    • Small integer Object pool
      • Python's definition of small integers is [-5, 257) that these integer objects are built well in advance;
      • In a python program, all integers that are in this range use the same object;
      • Single character shared object, resident memory;
    • Large integer Object pool
      • A new object is created for each large integer;
    • internMechanism
      • Single word, non-modifiable, default open intern mechanism, common object, when the reference count is 0 o'clock, destroy;
      • string (containing spaces), non-modifiable, no open intern mechanism, no common objects;
# 示例:a1 = "Helloworld"a2 = "HelloWorld"a3 = "HelloWorld"a4 = "HelloWorld"a5 = "HelloWorld"a6 = "HelloWorld"# 说明:# intern 机制,内存中只有一个"HelloWorld"所占的空间,靠引用计数去维护何时释放。
1.1 GC Garbage Collection
    • Python is based on the reference counting mechanism, which is supplemented by the collection mechanism.
    • GC Module Common functions:
      • gc.get_threshold(): Gets the frequency at which garbage collection is automatically performed in the GC module;
      • gc.set_threshold(threshold[, threshold1[, threshold2]])Set how often garbage collection is performed automatically;
      • gc.get_count(): Gets a counter that is currently automatically performing garbage collection, returning a list of length 3;
      • gc.collect(): Displays the execution garbage collection;
# 示例:# 引用计数缺点:循环引用class ClassA():    def __init__(self):        print("object born,id:%s" % str(hex(id(self))))def f2():    while True():        c1 = ClassA()        c2 = ClassA()        c1.t = c2        c2.t = c1        del c1        del c2f2()
2. Built-in properties and built-in functions 2.1 built-in properties
    • Common Properties
      • __init__ : Construct an initialization function;
      • __new__ : Generate the attributes required for the instance;
      • __class__ : The class where the instance resides, and the instance. __class__
      • __str__ : Instance string representation, readability; Print (class instance)
      • __repr__ : Instance string representation, accuracy, trigger when class instance carriage return
      • __del__ : del instance , triggered;
      • __dict__ : Instance custom property;
      • __doc__ : Class document, subclass does not inherit; help (class or instance)
      • __getattribute__ : property access blocker;
      • __bases__ : All the parent classes of the class are composed of elements, class names. __bases__
# Example: Property Interceptor Class Test (object): Def __init__ (self, subject1): Self.subject1 = Subject1 self.subject2 = ' cp            P ' # property access blocker, print log information def __getattribute__ (self, obj): print ("===1>%s"% obj) if obj = = ' Subject1 ': Print (' Log subject1 ') return ' redicrect python ' else:temp = Object.__getattribute_ _ (self, obj) print ("===2>%s"% str (temp)) return temp def show (self): print ("The Is a Test ") s = Test (" python ") print (S.subject1) print (S.SUBJECT2) s.show () # call Method Step: # 1. Use the property access interceptor first to get the method corresponding to the show property; # 2. Method () # example two: Attribute Interceptor Considerations Class Person (object): Def __getattribute__ (self, obj): print ("= = = Test = = =") If OBJ.S Tartswith ("a"): return "haha" else:return self.test def Test (self): print ("Heihei" t = person () T.A # returns HAHAT.B # causes the program to hang # Cause: When T.B executes, the __getattribute__ method defined in the person class is called and if condition is not satisfied, so the program # executes the Else The code of the face, that is, return self.test; Because returnNeed to return the value of Self.test, then first # to get the value of self.test, because self is now the object T, so, self.test = T.test, t.test at this time # to get t this object's Test property, then, will jump to The __getattribute__ method is executed, that is, the recursive call is generated at this time;
2.2 Built-in functions
    • dir(__builtins__): You can view the properties and functions that are loaded by default after the Python interpreter starts;
# example one: Rangerange (stop) range (start, stop[, step]) # Note: # Python2 in the range return list; # Python3 in the range returns an iteration value; If you want to list, you can function # Pyton3 Another way to create a list: Testlist = [x*2 for x in range]]testlist# example two: The Map function # Map function maps the specified sequence according to the provided function # Map (function, SE quence[, Sequence, ...])   list# functions: Function # Sequence: One or more sequences, depending on the function requires several parameters; # The return value is a list# function requires a parameter map (lambda x:x*x, [1, 2, 3]) # results: [1, 4, 9]# function requires two parameter map (lambda x, Y:x+y, [1, 2, 3], [4, 5, 6]) # The result is: [5, 7, 9]# example three: the Filter function # filter (functio    n or None, sequence), tuple, or string# function: accepts a parameter, returns a Boolean value of TRUE or false# sequence: The sequence can be str, tuple, list# The filter function calls the function function for each element in the sequence parameter sequence, and the result of the last return contains the element that invokes the # True filter (lambda x:x%2, [1, 2, 3, 4]) # Results for [1, 3] # example four: reduce function # reduce (function, sequence[, initial]), value# function: The function has two parameters # sequence: The sequence can be str, tuple, list# initial: Fixed initial value # The reduce function takes an element from the sequence in turn, and invokes function again with the result of the last call to function. When the # function is called for the first time, if the initial parameter is supplied, the SEThe first element in Quence and initial call function as a parameter, otherwise the function is called with the first two elements in the # sequence sequence.      Note that function functions cannot be nonereduce (lambda x, Y:x+y, [1, 2, 3, 4]) # results are: 10reduce (lambda x, y:x+y, [' AA ', ' BB ', ' cc ', ' DD ') # The result is: ddaabbcc# Note: Python3, the reduce function has been removed from the global namespace and is now placed inside the Functools module, which needs to be imported if needed: from Functools import reduce# Example five: sorted function # sorted (iterable, Cmp=none, Key=none, Reverse=fale), new sorted listsroted ([' dd ', ' yy ', ' ee ', ' ss ', ' WW ') , reverse=1)
3. Set Set
    • Collections are similar to previous lists, tuples, and can store multiple data, but the data is not duplicated;
    • The set object also supports Union (union), intersection (intersection), difference (difference) and sysmmetric_difference (symmetric difference sets) and other mathematical operations;
# 示例:a = "abcdef"b = set(a)      # 输出: {'a', 'b', 'c', 'd', 'e', 'f'}A = "bdfwm"B = set(A)b&B     # 取交集b|B     # 取并集b-B     # 取差集b^B     # 对称差集(在b或B中,但不会同时出现在二者中)
4. Functools
# Python3import Functoolsdir (functools) # View all tool functions # function One: partial function (partial function) # Set the default value for some parameters of a function, return a new function, call this new function will be more simple import Functoolsdef Showarg (*args, **kw): print (args) print (kw) P1 = Functools.partial (Showarg,) p1 () # Output: (1, 2, 3 {}P1 (4, 5, 6) # Output: (1, 2, 3, 4, 5, 6) {}p1 (a= ' python ', b= ' java ') #输出: (1, 2, 3) {' B ': ' Java ', ' a ': ' Python '}# function II : Wraps function # When using adorners, there are some details that need to be noticed. For example, the decorated function, in fact, is already another function (the function property will change) def note (func): "Note function" # Description document DEF wrapper (): "' Wrapper fu    Nction ' Print (' note something ') return func () return wrapper@notedef test (): ' ' Test function ' Print (' I am Test ') print (Help (test)) # Output wrapper Description Document # Wrapper () # wrapper function# Functools Package provides wraps adorner to eliminate such side effects I Mport functoolsdef Note (func): ' Note function ' @functools. Wraps (func) def wrapper (): "' Wrapper functi  On ' Print (' note something ') return func () return wrapper@notedef test (): ' ' Test function '  Print (' I am Test ') print (Help (test)) # Output: # test () # test function 


Resources:

    • Python Core Programming

Python Object-oriented Advanced (ii)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.