Three artifacts-iterators, generators, and adorners

Source: Internet
Author: User
Tags closure wrapper
1. Iterators and generators 1.1 iteratorsBase iterator initialization and access
i = ITER (' abc ') print (i.__next__ ()) print (i.__next__ ()) print (
i.__next__ ()) for
I in ITER (' abc '):
    Print (i)
For a class, __iter__ (self) and __next__ (self) are required. Also, use the raise stopiteration to stop the iterator.
Class Myiterator (object):
    def __init__ (self):
        self.a = 0
        self.b = 1
    def __iter__ (self):
        return Self
    def __next__ (self):
        self.a,self.b = self.b,self.a+self.b
        if self.a>100000:
            raise Stopiteration # This will stop return automatically
        SELF.A for
N in Myiterator ():
    print (n)
1.2 GeneratorsBuilder: Yield. Access: obj.__next__ () 2. Closure of the packageNote Closure usage: Return internal function func is a function reference, func () is a function call
def greeting_conf (prefix):
    def greeting (name):
        print (prefix, name) return
    greeting mgreeting
= Greeting_conf ("Good Morning") # The mgreeting is now function:greeting
print ("Function name is:", mgreeting.__name__) 
print ("ID of mgreeting is:", ID (mgreeting))
print ()
agreeting = mgreeting ("Good Afternoon") 
print (" Inner function returns: ", agreeting)
print (ID of agreeting is:, ID (agreeting))
3. Decoration Device Class 3.1 methods: @classmethod and @staticmethodAvoid instantiating, you can call the method of the class directly.
Class MyClass:
    bar = 1
    def foo (self):
        print (' MyClass ')
    @classmethod #避免硬编码
    def classfoo (CLS):
        print (' Classfoo ', end= "")
        print (Cls.bar)
        cls (). Foo ()
        # Cls.foo () # This call will be an error. No self
    @staticmethod
    def staticfoo ():
        print (' Staticfoo ', end= "")
        print (Myclass.bar)
        MyClass (). Foo ()
        # Myclass.foo () # This call will be an error. No self
# no instantiation, direct call to
Myclass.classfoo ()
Myclass.staticfoo ()
3.2 @property class adorner@property equivalent to get, corresponding to the adorner, all need func+setter/deleter
Class MyClass:
    def __init__ (self):
        self.__x = None
    @property
    def x (self): return
        self.__x
    @ X.setter
    def x (self,value):
        self.__x = value
    @x.deleter
    def x (self):
        del self.__x

MyClass = MyClass ()
print (myclass.x) # calls @property
myclass.x = 100 # calls @x.deleter
print (myclass.x)
del ( myclass.x) # call @x.deleter
try:
    print (myclass.x)
except Exception as Error:
    print (' Fail ', error)
3.3 Custom adorners

Although there is a lot of understanding of the adorner, but the landlord still feel that the adorner is a function of the definition of behavior. (#^.^#) simplest adorner, closure + function parameters

def log (func):
    # most basic adorner
    def wrapper (*args,**kw):
        print ("Call%s ();"% func.__name__)
        # return Func (*args,**kw) # can not comment out, will call return
    wrapper
@log
def now ():
    print ("Now")
Adorner with parameters: 3-layer package, note that the declaration must have parentheses ...
def log (text= "I am Default text"):
    # Adorner with parameters
    def decorator (func):
        def wrapper (*args,**kw):
            print (func.__name_ _) Return
            func (*args,**kw) return
        wrapper return
    decorator
@log () #注意: When an adorner declaration has a parameter, the bracket def must
be Now ():
    print (' Now ') now
()
The following is a useful adorner usage that defines the function behavior.
def before (request, Kargs):
    print (' before ')
def after (request, Kargs):
    print (' after ')
def Filter ( Before_func, After_func):
    def outer (main_func):
        def wrapper (Request, Kargs):
            Before_result = Before_func (Request, Kargs)
            if (Before_result!= None): Return
                before_result
            main_result = main_func (Request, Kargs)
            if (Main_result!) = None): Return
                main_result
            after_result = after_func (Request, Kargs)
            if (After_result!= None):
                Return After_result return
        wrapper return
    outer
@Filter (before, after)
def Index (Request, Kargs) :
    print (' index ')
index (1,2)

Output results:

Before
index
after

Welcome to further exchange the relevant content of this blog:
GitHub address: Https://github.com/AsuraDong/Blog
csdn Address: Http://blog.csdn.net/asuradong
Jane Book address: http://www.jianshu.com/u/d1570f4a618a
Blog Park address: http://www.cnblogs.com/AsuraDong/(not necessarily timely update)
can also be written to communicate: Xiaochiyijiu@163.com
Welcome to Personal microblogging: Http://weibo.com/AsuraDong
Welcome to reprint , but please indicate the source  :   )

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.