Python (22)

Source: Internet
Author: User
Tags ftp client

A isinstance (OBJ,CLS) and Issubclass (Sub,super)

Isinstance (obj,cls) checks if obj is an object of class CLS

1 class Foo (object): 2     pass3  4 obj = Foo () 5  6 isinstance (obj, Foo)

Issubclass (sub, super) check if the sub class is a derived class of super class

1 class Foo (object): 2     pass3  4 class Bar (Foo): 5     pass6  7 issubclass (Bar, Foo)
Two-reflection

1 What is reflection

The concept of reflection, first proposed by Smith in 1982, is a capability (introspection) that a program can access, detect, and modify its own state or behavior. The proposal of this concept soon triggered the research on the application of reflectivity in Computer science field. It is first used in the field of programming language design, and has achieved achievements in Lisp and object-oriented.

2 Python Object-oriented reflection: manipulating object-related properties in the form of a string. All things in Python are objects (you can use reflection)

Four functions that can be self-reflective

The following methods apply to classes and objects (everything is an object, and the class itself is an object)

Determine if there is a method or property in the object that has a name string
hasattr (object,name)
Def getattr (object, Name, Default=none): # Known special case of GetAttr    "" "    getattr (object, name[, default])-> ;    the value Get a named attribute from an object; GetAttr (x, ' Y ') are equivalent to x.y.    When a default argument is given, it's returned when the attribute doesn ' t    exist; without it, an exception it raised In the case.    "" " Pass
GetAttr (object, Name, Default=none)
def setattr (x, Y, v): # real signature unknown; Restored from __doc__    "" "    sets the named attribute on the given object to the specified value.    SetAttr (x, ' Y ', V) is equivalent to ' x.y = V ' "" "    Pass
setattr (x, y, v)
def delattr (x, y): # Real signature unknown; Restored from __doc__    "" "    deletes the named attribute from the given object.    Delattr (x, ' Y ') is equivalent to ' del x.y ' "" "    Pass
delattr (x, y)
Class Blackmedium:    feature= ' Ugly '    def __init__ (self,name,addr):        self.name=name        self.addr=addr    def sell_house (self):        print ('%s black intermediary sells a house, the idiot buys it, but who can prove that he is not a fool '%self.name ')    def rent_house:        Print ('%s black intermediary rented the house, the idiot just rented it '%self.name ') b1=blackmedium (' million into place ', ' Huilongguan ') #检测是否含有某属性print (Hasattr (B1, ' name ')) print ( Hasattr (B1, ' Sell_house ')) #获取属性n =getattr (B1, ' name ') print (n) func=getattr (B1, ' Rent_house ') func () # GetAttr (B1, ' Aaaaaaaa ') #报错print (GetAttr (B1, ' aaaaaaaa ', ' not Present ')) #设置属性setattr (B1, ' SB ', True) SetAttr (B1, ' show_name ', lambda self: self.name+ ' SB ') print (b1.__dict__) print (B1.show_name (B1)) #删除属性delattr (B1, ' addr ') delattr (B1, ' Show_name ') delattr ( B1, ' show_name111 ') #不存在, error print (b1.__dict__)
four ways to use a demo
Class Foo (object):     Staticfield = "Old boy"     def __init__ (self):        self.name = ' Wupeiqi '     def func:        return ' func '     @staticmethod    def Bar ():        return ' bar ' Print getattr (Foo, ' Staticfield ') print getattr ( Foo, ' func ') print getattr (foo, ' Bar ')
class is also an object
#!/usr/bin/env python#-*-coding:utf-8-*-import sysdef s1 ():    print ' s1 ' def S2 ():    print ' s2 ' this_module = sys.m Odules[__name__]hasattr (This_module, ' s1 ') getattr (this_module, ' S2 ')
reflect current module members

Import other modules and use reflection to find out if a method exists for the module

#!/usr/bin/env python#-*-coding:utf-8-*-def Test ():    print (' from the test ')
module_test.py
1 #!/usr/bin/env Python 2 #-*-coding:utf-8-*-3   4 "" 5 Program directory: 6     module_test.py 7     index.py 8   9 Current file: 10
   index.py11 "" ", import module_test as Obj14 #obj. Test () print (hasattr (obj, ' Test ')), getattr (obj, ' test ') ()

3 Why reflection with reflection of the benefits

Benefits One: Implement pluggable mechanisms

There are two programmers, a Lili, a egon,lili in the writing process need to use the Egon written class, but Egon to go with his girlfriend honeymoon, has not finished his class, Lili think of reflection, using the reflection mechanism Lili can continue to complete their own code, After the return of Egon to the honeymoon and then continue to complete the definition of the class and to achieve Lili desired function.

In short, the advantage of reflection is that the interface can be defined in advance, the interface only after the completion of the actual execution, this implementation of Plug and Play, which is actually a ' late binding ', what does it mean? That is, you can write the main logic in advance (just define the interface), and then later to implement the function of the interface

Class FtpClient:    ' FTP client, but still has the ability to implement specific '    def __init__ (self,addr):        print (' Connecting server [%s] '%addr)        Self.addr=addr
Egon has not yet achieved full functionality
#from Module Import ftpclientf1=ftpclient (' 192.168.1.1 ') if Hasattr (F1, ' get '):    func_get=getattr (F1, ' get    ') Func_get () Else: print (    '----> Not present this method ')    print (' Handle Other logic ')
code writing without affecting Lili

Benefit Two: Dynamic import module (based on Reflection current module member)

Three __setattr__,__delattr__,__getattr__
Class Foo:    x=1    def __init__ (self,y):        self.y=y    def __getattr__ (self, item):        print ('----> from GetAttr: The attribute you are looking for does not exist ')    def __setattr__ (self, Key, value):        print ('----> from setattr ')        # self.key=value # This is infinite recursion, you think about it.        self.__dict__[key]=value #应该使用它    def __delattr__ (self, item):        print ('----> from Delattr ')        # del Self.item #无限递归了        self.__dict__.pop (item) #__setattr__添加/Modify property will trigger its execution F1=foo (f1.__ DICT__) # because you rewrite the __setattr__, any assignment operation will trigger it to run, you do not write anything, is not assigned at all, unless you directly manipulate the property dictionary, otherwise you can never assign a value F1.z=3print (f1.__dict__) #__delattr_ _ f1.__dict__[' A ' is triggered when the property is deleted]=3# We can directly modify the property dictionary to complete the operation of adding/modifying Properties del f1.aprint (f1.__dict__) #__getattr__ F1.xxxxxx is triggered only when a property is called with a point and the property does not exist
a demonstration of the usage of the three

Four __setitem__,__getitem,__delitem__
Class Foo:    def __init__ (self,name):        self.name=name    def __getitem__ (self, item):        Print (self.__dict_ _[item])    def __setitem__ (self, Key, value):        self.__dict__[key]=value    def __delitem__ (self, key):        Print (' del Obj[key], I execute ')        self.__dict__.pop (key)    def __delattr__ (self, item):        print (' Del Obj.key, I execute ')        Self.__dict__.pop (item) f1=foo (' SB ') f1[' age ']=18f1[' age1 ']=19del f1.age1del ' f1[' age ']f1[' name ']= ' Alex ' Print (f1.__dict__)
View Code

Five __del__

destructor, which automatically triggers execution when the object is freed in memory.

Note: This method is generally not defined because Python is a high-level language, and programmers do not need to be concerned with allocating and releasing memory because this work is done by the Python interpreter, so the destructor calls are automatically triggered by the interpreter when it is garbage collected.

Class Foo:    def __del__ (self):        print (' Execute Me ') F1=foo () del f1print ('-------> ') #输出结果执行我啦------->
Simple Demonstration
Class Foo:    def __del__ (self):        print (' Execute Me ') F1=foo () # del f1print ('-------> ') #输出结果-------> Execute me # Why???
digging a hole, burying you.

Class Foo:    def __init__ (self,name):        self.name=name    def __getitem__ (self, item):        Print (self.__dict_ _[item])    def __setitem__ (self, Key, value):        self.__dict__[key]=value    def __delitem__ (self, key):        Print (' del Obj[key], I execute ')        self.__dict__.pop (key)    def __delattr__ (self, item):        print (' Del Obj.key, I execute ')        Self.__dict__.pop (item) f1=foo (' SB ') f1[' age ']=18f1[' age1 ']=19del f1.age1del ' f1[' age ']f1[' name ']= ' Alex ' Print (f1.__dict__)

Python (22)

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.