Python Object-oriented step (i)

Source: Internet
Author: User
Tags generator iterable

1. Generator
    • With list generation, you can create a list directly. However, with memory limitations, the list capacity is certainly limited. Also, create a
      Contains a list of 1 million elements that not only occupy a lot of storage space, if we just need to access the first few elements, then the vast majority of
      The space that the elements occupy are wasted. So, if the list element can be extrapolated by an algorithm, can we
      In the process of continuous calculation of the subsequent elements? This eliminates the need to create a complete list, which saves a lot of space.
    • In Python, this side loop computes the mechanism, called the Generator (generator)
# 创建生成器的方法一:只要把一个列表生成式的 [] 改成 ()L = [ x*2 for x in range(5)]L   # 输出: [0, 2, 4, 6, 8]G = ( x*2 for x in range(5))G   # 输出: <generator object <genexpr> at 0x1077d9db0>next(G) # 每执行一次 next(),输出一个元素# 创建生成器的第二种方式: 使用函数# 斐波拉契数列(Fibonacci)def fib(times):    n = 0    a, b = 0, 1    while n < times:        print(b)        a, b = b, a+b        n += 1    return 'done'fib(5)# 生成器(ipython 中操作)def fib():    print("=== start ===")    a, b = 0, 1    for i in range(5):        print("=== 1 ===")        yield b        print("=== 2 ===")        a, b = b, a+b        print("=== 3 ===")    print("=== stop ===")a = fib()a   # 输出: <generator object fib at 0x23355>next(a)   # 等价于 a.__next__()# 输出:# === start ===# === 1 ===#   1# 此时,fib()函数就是生成器,可以使用循环来迭代for num in a:    print(num)
1.1 Send
# 示例:# ipython3 中操作def gen():    i = 0    while i<5:        temp = yield i        print(temp)        i+=1a = gen()a.__next__()    # 输出: 0a.__next__()    # 输出: None  1a.send("haha")  # 输出: haha  2# 说明: 程序执行到yield时,gen函数暂时停止,同时返回i的值;# temp 接收send过来的值(haha);# a.__next__() 等价 a.send(None)# 若是第一次直接调用 a.send("haha"), 程序会报错
2. iterators
    • Iterations are a way to access the elements of a collection.
    • An iterator is an object that can remember the location of the traverse;
    • An iterator object is accessed from the first element of the collection until all the elements have been accessed and finished;
    • Iterators can only move forward and not backward;
2.1 Iterative Objects
    • There are several types of data that can be directly acting on a For loop:
      • Collection data type:,,, list tuple dict set , str etc;
      • generator, including generators and bands yield generation function ;
      • These objects that can directly act on a for loop are called an iterative object (iterable)
    • Can be used to isinstance() determine whether an object is an Iterable object;
# 示例:from collections import Iterableisinstance([], Iterable)    # True
2.2 iterators
    • An object that can be called by next() a function and continually returns the next value is called an iterator (Iterator);
    • Can be used to isinstance() determine whether an object is a Iterator object;
# 示例:from collections import Iteratorisinstance((x for x in range(10), Iterator)  # Trueisinstance([], Iterator)  # False
2.3 iter () function
    • Generators are Iterator objects;
    • list, dict str Although it is iterable, but not Iterator;
    • You can use the iter() function to turn list , and dict str so iterable into Iterator;
# 示例:from collections import Iteratorisinstance(iter([]), Iterator)  # True
3. Closures
# 示例一:def test():    print("=== in test func ===")# 调用函数test()# 引用函数, 直接书写函数名,表示引用函数;# 在 ipython 中运行 test,会输出: <function __main__.test>ret = testprint(id(ret))print(id(test))ret()# 运行结果:=== in test func ===44092110804409211080=== in test func ===# 示例二: 闭包定义# 定义一个函数def test1(number):    # 在函数内部再定义一个函数,并且这个函数用到了外边函数(test1)的变量(number),    # 那么将这个函数以及用到的一些变量称之为闭包    def test_in(number_in):        print("in test_in 函数, number_in is %d" % number_in)        return number + number_in    # 其实,这里返回的就是闭包的结果    return test_in# 给 test1 函数赋值,这个20就是给参数 number# 此时, ret 指向 test_in, 也就是说, ret = test_in, number = 20ret = test1(20)# 注意,这里的100,其实是给参数 number_inprint(ret(100))     # 输出 120#注意这里的200,其实是给参数 number_inprint(ret(200))     # 输出 220
4. Decorative Device
# example one: def foo (): Print (' foo ') Foo # indicates that the function foo () # indicates the Execute Foo function # example two: def foo (): Print (' foo ') foo = lambda x:x + 1foo ( # executes the following lambda expression instead of the original Foo function, because the name Foo is re-pointing to another anonymous function # example three: Adorner before code # Requirements: A basic Platform department responsible for providing the underlying functions such as database operations, Redis calls, Monitoring API and other features # when other business units use the underlying functionality, simply invoke the functionality provided by the underlying platform, and the functionality provided by the ========== base platform ===========def F1 (): Print ("F1") def f2 (): Print ("F2") de F f3 (): Print ("F3") def f4 (): Print ("F4") =========== business unit A call base function ==========f1 () F2 () F3 () F4 () ========== business Unit B call base function =    =========F1 () F2 () F3 () F4 () example four: Adorner # requirements: Before performing the underlying function, you need to validate the open closure principle of # Write code: # Closed: implemented function code block # Open: to Extended open def W1 (func):  def inner (): # verify 1 # verify 2 # Verify 3 func () return inner# @w1 equivalent to F1 = W1 (F1), at which point F1 points (inner     Pointer to the function body) # Caller, continue to F1 (), do not need to make modifications @w1def F1 (): Print (' F1 ') @w1def F2 (): Print (' F2 ') @w1def F3 (): Print (' F3 ') @w1def f4 (): Print (' F4 ') # example five: Adorner extension def makebold (FN): print ("= = = Bold = = =") def wrapped (): print ("= = = 1 = = = =") r Eturn "<b>" + fn () + "&LT;/B&Gt; " return wrappeddef Makeitalic (FN): print ("= = = Italic = = =") def wrapped (): print ("= = = 2 = = =") return "&L T;i> "+ fn () +" </i> "return Wrapped@makebold@makeitalicdef test1 (): print (" = = = 3 = = = ") return" Hello wo rld! " Print (Test1 ()) # Output: # (the previous two sentences, do not call the Test1 () function will also output) # = = = Italic ===# = = Bold ===# = = 1 ===# = = 2 ===# = = 3 ===# &LT;B&G T;<i>hello world!</i></b># Example Six: What time does the adorner perform def W1 (func): print ("= = = = = = = = = = = = = =") def inner (): P Rint ("= = = Verifying Permission = = =") func () return inner# as long as the Python interpreter executes to @w1 this line of code, it will automatically decorate, # instead of waiting until the call F1 () to decorate the console will output: = = = is decorating = = = @w1def F1 (): print ("= = = F1 = = = = = =") # example VII: decorated function with parameter Def W1 (func): Def inner (x, y): # If x, y is not defined, it causes F1 (22, 3 3) call failed # verify 1 func (x, y) # If you do not pass X, y as an argument, it causes the call to F1 (A, B) to fail return Inner@w1def F1 (A, B): Print (' A =%d, B =%d '% (a, b)) F1 (22, 33) # example eight: decorated function with indefinite length parameter Def W1 (func): Def inner (*args, **kwargs): # verify 1 Fu NC (*args, * *Kwargs) return inner@w1def F2 (A, B, c): print (' A =%d, B =%d, c =%d '% (a, B, c)) @w1def F3 (A, B, C, D): Print (' A =%d, B =%d, c =%d, d =%d '% (a, B, C, D)) F2 (one, 22, 33, 44) # example nine: Decorate def W1 (func) with functions with return values: Def inne R (): print ("= = = = = = = = =") result = Func () print ("= = = = = = = = = = = =") return result return inner@w 1def F1 (): print ("= = = function Code = = = = = =") return "Zhangsan" name = F1 () print ("Queried name:%s"% name) # example Ten: Universal Adorner ((not) with parameter, (not) with return value) d EF W1 (func): Def inner (*args, **kwargs): print ("= = = = = = = = = = =") result = Func (*args, **kwargs) print    ("= = = = = = = = =") return result return inner@w1def F1 (): print ("= = = function Code = = = =") return "haha" @w1def F1 (a): Print ("= = = function Code = = =") print ("Input character:%s"% a) # example 11: Adorner with parameters, set external variable from time import CTime, based on original adorner, Sleepdef Timefun_ Arg (pre= "Hello"): Def Timefun (func): Def wrappedfunc (): Print ("%s called at%s%s"% (func.__name__,          CTime (), pre))  return func () return Wrappedfunc return Timefun@timefun_arg ("noodles") def foo (): Print ("I am Noodles") @time Fun_arg ("Google") def too (): print ("I am Google") foo () sleep (2) too () # output: Foo called at Sat Mar 17:56:06 2018 Noodlesi Am Noodlestoo called at Sat Mar 17:56:08 2018 Googlei am google# remarks: # 1. Execute the Timefun_arg ("noodles") function first, and the result returned by this function is a reference to the Timefun function # 2. @timefun # 3. Decorate Foo with @timefun
Class 4.1 Decorators
    • The adorner function is actually such an interface constraint that it must accept a callable object as a parameter and then return a callable object.
    • In Python, the general callable object is a function, but there are exceptions, so long as an object overrides the __call__() method, the
      The object is callable ;
# 示例一: callableclass Test():    def __call__(self):        print("call me!")t = Test()t()    # 输出: call me!# 对象(),会调用 __call__ 方法# 示例: 类装饰器class Test(object):    def __init__(self, func):        print("=== 初始化 ===")        print("func name is %s" % func.__name__)        self.__func = func    def __call__(self):        print("=== 装饰器中的功能 ===")        self.__func()# 说明:# 1, 当有Test来装作装饰器对test函数进行装饰的时候,首先会创建Test的实例对象,并且会把test这个函数# 名当做参数传递到 __init__ 方法中;## 2, test函数相当于指向了用Test创建出来的实例对象;## 3, 当在使用test()进行调用时,就相当于让这个对象(),因此会调用这个对象的 __call__ 方法;## 4. 为了能够在__call__ 方法中调用原来test指向的函数体,所以在__init__方法中就需要一个实例属性来保存# 所以才有了 self.__func = func 这句代码,从而在调用 __call__ 方法中能够调用到test之前的函数体@Testdef test():    print("=== test ===")test()
5. Meta-Class
    • In most programming languages, a class is a set of code snippets that describe how to generate an object;
    • Classes in Python are much more than that, and classes are still objects;
    • Using type dynamic creation classes,
      • Format:type(类名, 有父类名称组成的元组(针对继承的情况,可以为空), 包括属性的字典(名称和值))
    • typeis the meta-class that Python uses to create all the classes behind it;
# 示例:# 传统方式定义类class Test:    passt1 = Test()# type 定义类Test2 = type("Test2", (), {})t2 = Test2()type(t1)     # 输出: __main__.Testtype(t2)     # 输出: __main__.Test2# 带有属性的类class Person:    age = 15Person2 = type("Person2", (), {"age":15})# 带有方法的类# 定义方法def printAge(self):    print("=== 年龄是: %d ===" % self.num)Person3 = type("Person3", (), {"printAge": printAge})p = Person3()p.age = 22p.printAge()# 存在继承关系的类class Animal:    def eat(self):        print("=== eat ===")Cat = type("Cat", (Animal,), {})tom = Cat()tom.eat()
5.1 __metaclass__Property
# 示例:class Foo(Bar):    pass# Python 创建类的过程中,做了如下操作# 1, Foo 中有 __metaclass__ 这个属性吗?如果有,Python 会通过 __metaclass__ 创建一个名字为Foo的类对象;# 2, 如果Python没有找到__metaclass__, 它会继续在Bar(父类)中寻找 __metaclass__ 属性,并尝试做和前面同样的操作;# 3, 如果Python在任何父类中到找不到__metaclass__, 它就会在模块层次中去寻找 __metaclass__, 并尝试做同样的操作;# 4. 如果还是找不到 __metaclass__, Python 就会用内置的type来创建这个类对象;


Resources:

    • Python Core Programming
    • Deep understanding of the meta-classes in Python (metaclass)

Python Object-oriented step (i)

Related Article

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.