python-Object-oriented advanced

Source: Internet
Author: User

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

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

Class Foo (object):
Pass obj = foo () isinstance (obj, foo)

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

class Foo (object):     Pass class Bar (Foo):     Pass Issubclass (Bar, Foo)

__setitem__,__getitem,__delitem__

In Python, if we want to implement a class similar to sequence and mapping, you can simulate it by rewriting the Magic method __getitem__, __setitem__, and __delitem__ methods.

__getitem__ (Self,key): Returns the value corresponding to the key.

__setitem__ (Self,key,value): Sets the value of the given key

__delitem__ (Self,key): Deletes the element corresponding to the given key.

classFoo:def __init__(self,name): Self.name=namedef __getitem__(self, item):#print ("GetItem")        returnSelf.__dict__[item]def __setitem__(self, Key, value):#print ("SetItem", Key,value)Self.__dict__[key]=valuedef __delitem__(self, key):#print (' del Obj[key], I execute ')Self.__dict__. Pop (key)#If there is no Item method, the type of obj needs to be judged, and the function will be more out of function-independent logic#def func (obj,key,value):#if Isinstance (obj,dict):#obj[key]=value #obj [' name ']= ' 123123 '#Else:#setattr (Obj,key,value)#With the Item method, you do not need to judge the type of obj, whether it is the dict type or the Foo type, in a uniform [] waydeffunc (Obj,key,value): Obj[key]=value#obj[' name ']= ' 123123 'dic={'name':'Egon',' Age': 18}Print(DIC) obj=foo ('Egon') func (DIC,'name','egon666')Print(DIC)Print(obj.__dict__) func (obj,'name','123123123123')Print(obj.__dict__)#Output Results{'name':'Egon',' Age': 18}#{' name ': ' egon666 ', ' age ':#{' name ': ' Egon '}#{' name ': ' 123123123123 '}
__setitem__,__getitem,__delitem__

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)

Say reflection before the introduction of the __import__ method, this and import imported module another way

Import   Commons__import__('commons' )

If it is a multilayer import:

 from Import  __import__('  list.text.commons'# If you don't add fromlist=true, Only the list directory is imported

Reflection is thought of 4 built-in functions: GetAttr, Hasattr, SetAttr, delattr get members, check members, set members, delete members The following describes the first example:

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__)

Property

The nature of a static property is to implement the Get,set,delete three methods

1 classGoods:2 3     def __init__(self):4         #Original Price5Self.original_price = 1006         #Discount7Self.discount = 0.88 9 @propertyTen     defPrice (self): One         #actual rate = Original Price * Discount ANew_price = Self.original_price *Self.discount -         returnNew_price -  the @price. Setter -     defPrice (self, value): -Self.original_price =value -  + @price. Deleter -     defPrice (self): +         delSelf.original_price A  at  -obj =Goods () -Obj.price#Get product price -Obj.price = 200#revise the original price of the product - Print(Obj.price) - delObj.price#Delete Item Price
Property Application__module__ and __class__

__MODULE__ represents the object of the current operation in that module

__CLASS__ represents the class of the object that is currently being manipulated

 #  !/usr/bin/env python  #  -*-coding:utf-8-*-  Class   C:  def  __init__   = ' Sb " /span> 
 from Import  = C ()print obj.__module__  #  output LIB.AA, i.e.: Output module Print obj.__class__      #  output lib.aa.c, i.e.: Output class
__call__

The object is appended with parentheses to trigger execution.

Note: The execution of the construction method is triggered by the creation object, that is: Object = class name (), and the execution of the __call__ method is triggered by parentheses after the object, i.e.: Object () or Class () ()

class Foo:     def __init__ (self):         Pass        def __call__ (Self, *args, * *Kwargs)        : Print ('__call__'#  execution __init__obj ()       # Executive __call__

python-Object-oriented advanced

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.