python--Object-oriented (advanced)

Source: Internet
Author: User

Python-Object-oriented advanced
Isinstance and Issubclass

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

 class Foo (object): Pass obj = foo () sinstance (obj, foo)   

isscubclass (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)
reflection
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)

Hasattr
def hasattr (*args, **kwargs): # Real signature Unknown    "" "    Return whether the object has a attribute with the GIV En name.        This is do by calling GetAttr (obj, name) and catching Attributeerror.    "" Pass


GetAttr
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
SetAttr
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

Delattr
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
Use of four methods
 class foo:f = ' static variable of class ' Def __init__ (self,name,age): Self . Name=name Self.age=age def say_hi (self): print (' hi,%s '%self.name) obj=foo (' Egon ',) #检测是否含有某属性print (Hasat TR (obj, ' name ')) print (Hasattr (obj, ' Say_hi ')) #获取属性n =getattr (obj, ' name ') print (n) func=getattr (obj, ' Say_hi ') func () Print (GetAttr (obj, ' aaaaaaaa ', ' not Present ')) #报错 # Set Property setattr (obj, ' sb ', True) setattr (obj, ' show_name ', lambda self: self.name+ ' SB ') print (obj.__dict__) print (Obj.show_name (obj)) #删除属性delattr (obj, ' age ') delattr (obj, ' show_name ') Delattr (obj, ' show_name111 ') #不存在, error print (obj.__dict__)  

Class is also an object
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 object-oriented
Class Foo (object):     Staticfield = "Old boy"     def __init__ (self):        self.name = ' Wupeiqi '     def func (self ):        return ' func '     @staticmethod    def Bar ():        return ' bar ' Print getattr (Foo, ' Staticfield ') print GetAttr (foo, ' func ') print getattr (foo, ' Bar ')
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 ')

#!/usr/bin/env python

#-*-Coding:utf-8-*-"" "Program Directory:    module_test.py    index.py Current file:    index.py" "" Import module_test as obj# Obj.test () print (hasattr (obj, ' Test ')) getattr (obj, ' Test ') ()
__str__ and __repr__
changing the object's string display __str__,__repr__
self-Customizing formatted string __format__
#_ *_coding:utf-8_*_

format_dict={
' nat ': ' {obj.name}-{obj.addr}-{obj.type} ', #学校名-school address-school type
' TNA ': ' {obj.type}:{obj.name}:{obj.addr} ', #学校类型: School Name: School Address
' tan ': ' {obj.type}/{obj.addr}/{obj.name} ', #学校类型/school address/School name
}
class School:
def __init__ (self,name,addr,type):
Self.name=name
self.addr=addr
Self.type=type

def __repr__ (self):
return ' School (%s,%s) '% (SELF.NAME,SELF.ADDR)
def __str__ (self):
return ' (%s,%s) '% (SELF.NAME,SELF.ADDR)

def __format__ (self, format_spec):
# if Format_spec
if not format_spec or Format_spec not in format_dict:
format_spec= ' Nat '
Fmt=format_dict[format_spec]
return Fmt.format (obj=self)

s1=school (' oldboy1 ', ' Beijing ', ' private ')
print (' from repr: ', repr (S1))
print (' from str: ', str (s1))
print (S1)

" "
str function or print function--->obj.__str__ ()
repr or Interactive interpreter--->obj.__repr__ ()
If the __str__ is not defined, then the __repr__ will be used instead of the output
Note: The return value of both methods must be a string or throw an exception
" "
Print (Format (S1, ' Nat '))
Print (Format (S1, ' TNA '))
Print (Format (S1, ' Tan '))
rint (Format (S1, ' asfdasdffd '))

class B:

def __str__ (self):
return ' Str:class B '

def __repr__ (self):
return ' Repr:class B '


b=b ()
print ('%s '%b)
print ('%r '%b)

%s and%r
class B:

def __str__ (self):
return ' Str:class B '

def __repr__ (self):
return ' Repr:class B '


b=b ()
print ('%s '%b)
print ('%r '%b)

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


f1=foo ()
del F1
print ('-------> ')

#输出结果

-------;
item series
__getitem__\__setitem__\__ 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__)
__new__
Class A:    def __init__ (self):        self.x = 1        print (' in init function ')    def __new__ (CLS, *args, **kwargs) :        print (' in new function ')        return object.__new__ (A, *args, **kwargs) a = A () print (a.x)
 class singleton:def __new__ (CLS, *args, **kw): If not Hasat        TR (CLS, ' _instance '): Orig = Super (Singleton, cls) cls._instance = orig.__new__ (CLS, *args, **KW) return cls._instanceone = Singleton () = Singleton () two.a = 3print (one.a) # 3# One and both are identical and can be detected with ID (), = =, is detection print (ID (one)) # 29097904print (ID ()) # 29097904print (one = =) # Trueprint (one is)  
__call__
The object is appended with parentheses, Trigger execution
Note: The execution of the construction method is triggered by the creation object, that is: Object = class name (), and for __call__ The execution of the method is triggered by the object's parentheses, namely: Object ()
Class Foo:    def __init__ (self):        pass        def __call__ (self, *args, **kwargs):        print (' __call__ ') obj = Foo () # Execute __init__obj ()       # Execute __call__
__len__
Class A:    def __init__ (self):        SELF.A = 1        self.b = 2    def __len__ (self):        return Len (self.__dict__ ) A = A () print (Len (a))

__hash__
Class A:    def __init__ (self):        SELF.A = 1        self.b = 2    def __hash__ (self):        return hash (str (SELF.A) +str (SELF.B)) A = A () print (hash (a))

__eq__
A:
    def __init__ (self):        SELF.A = 1        self.b = 2    def __eq__ (self,obj):        if  self.a = = obj.a and self.b = = OBJ.B:            Return Truea = A () b = A () print (A = = b)
Class Franchdeck:    ranks = [STR (n) for n in range (2,11)] + list (' Jqka ')    suits = [' hearts ', ' square ', ' Plum ', ' spades ']    def __ini T__ (self):        self._cards = [Card (rank,suit)-for-rank in-franchdeck.ranks for                                        suit in Franchdeck.suits]    def __ Len__ (self):        return len (self._cards)    def __getitem__ (self, item):        return Self._cards[item]deck = Franchdeck () print (deck[0]) from random import choiceprint (choice (deck)) print (choice (deck))
Class Franchdeck:    ranks = [STR (n) for n in range (2,11)] + list (' Jqka ')    suits = [' hearts ', ' square ', ' Plum ', ' spades ']    def __ini T__ (self):        self._cards = [Card (rank,suit)-for-rank in-franchdeck.ranks for                                        suit in Franchdeck.suits]    def __ Len__ (self):        return len (self._cards)    def __getitem__ (self, item):        return Self._cards[item]    def __ Setitem__ (self, Key, value):        Self._cards[key] = Valuedeck = Franchdeck () print (deck[0]) from random import Choiceprint (choice (deck)) print (choice (deck)) from random import shuffleshuffle (deck) print (Deck[:5])
Class Person:    def __init__ (self,name,age,sex):        self.name = name        Self.age = age        self.sex = Sex    def _ _hash__ (self):        return hash (self.name+self.sex)    def __eq__ (self, Other):        if self.name = = Other.name and Self.sex = = Other.sex:return Truep_lst = []for i in range:    p_lst.append (' Egon ', I, ' Male ')) print (P_LST) Print (Set (P_LST))

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.