Python Abstract: Object-oriented higher order

Source: Internet
Author: User

1. Check for inheritance

If you want to see if a class is a subclass of another class, you can use the built-in Issubclass function

If you want to know the base class of a known class, you can use special attributes directly __bases__

Also, use the Isinstance method to check whether an object is an instance of a class (instance)

If you want to know which class an object belongs to, you can use the __class__ attribute

2. Reflection

The reflection functionality in Python is provided by the following four built-in functions: Hasattr, GetAttr, SetAttr, delattr, and four functions for internal execution of objects: Check for a member, get a member, set a member, delete a member.

classFoo:def __init__(self,name,age): Self.name=name Self.age= AgedefShow (self):return "%s-%s"%(self.name,self.age) obj=foo ('Greg', 18)Print(Obj.name)#Gregb="name"Print(obj.__dict__)#{' name ': ' Greg ', ' age ':Print(obj.__dict__['name'])#GregPrint(obj.__dict__[b])#GregINP=input ('>>>')#What to get inside somethingv=getattr (OBJ,INP)Print(v)
#反射是通过字符串的形式操作对象相关的成员. all things are objects!!! Sho=getattr (obj,'Show')Print(Sho)#<bound method Foo.show of <__main__. Foo object at 0x000001e00c46ca58>>Sh=Sho ()Print(SH)#alex-18Print(Hasattr (obj,'name'))#TruePrint(Hasattr (obj,'name1'))#Falsesetattr (obj,'K1','v1')Print(OBJ.K1) #v1#Obj.namePrint(Delattr (obj,'name')) #NONE#Obj.name

Three ways to get the name variable in the Obj object to point to the value in memory "Gregory"

classFoo (object):def __init__(self): Self.name='Gregory'#do not allow the use of Obj.nameobj =Foo ()Print(Obj.name)Print(obj.__dict__['name'])Print(GetAttr (obj,'name'))

3. Nesting of objects

classF1:def __init__(self): Self.name="Greg"classF2:def __init__(self,a):#A=f1=[name=greg]Self.age=aclassF3:def __init__(SELF,B):#B=f2=[age=name=greg]Self.dd=Bf1=F1 ()#[Name=greg]F2=F2 (F1)#[Age=name=greg]F3=F3 (F2)#[Dd=[age=name=greg]]#print (F3.DD) #<__main__. F2 object at 0x00000232aca612b0>#print (f3.dd.age) #18Print(F3.dd.age.name)#Greg

4. Exception (Exception object)

4.1 Some important built-in anomalies

Attributeerror attempts to access a tree that does not have an object, such as foo.x, but Foo does not have a property xioerror input/output exception; it is basically impossible to open the file Importerror the module or package cannot be introduced is basically a path problem or name error Indentationerror syntax error (subclass); The code is not aligned correctly indexerror the subscript index exceeds the sequence boundary, for example, when X has only three elements, it attempts to access the X[5]keyerror Attempting to access a key that does not exist in the dictionary Keyboardinterrupt CTRL + C is pressed Nameerror use a variable that has not been assigned to the object SyntaxError Python code is illegal, the code cannot compile (personally think this is a syntax error, Wrong) TypeError the incoming object type is not compliant with the requirements Unboundlocalerror attempts to access a local variable that is not yet set, basically because another global variable with the same name causes you to think that you are accessing it valueerror a value that the caller does not expect , even if the type of the value is correct
4.2 Catching exceptions
Try: Li=[11,22] li[999]#can catch errors    #int (' d3de ') #不能捕获错误exceptIndexerror as E:Print('Indexerror', E)exceptValueError as E:Print('ValueError', E)exceptException as E: #在python的异常中, there is a universal exception: Exception, he can catch arbitrary exceptionsPrint('Exception', E)Else:    Print('Else')finally: #finally语句不管try是否发生异常, will be executed. Print('...')

4.3 Active trigger exception

Try :     # proactively triggering exceptions    Raise Exception (' but ... ' )except  Exception as E:    print(e)

The raise statement throws a common exception that does not have any errors.

4.4 Catching exceptions write to log

defdb ():#return True    returnFalsedefindex ():Try: R=input (">>") int (r) Result=db ()if  notResult:RaiseException ('Database processing error')    exceptException as E:str_error=Str (e)Print(Str_error)#Open file, write error logR=open ('Log','a') R.write (str_error) index ()

4.5 Custom Exceptions

classGregerror (Exception):def __init__(self,msg): Self.message=msgdef __str__(self):returnSelf.message#obj=gregerror (' xxx ')#print (obj)Try:    RaiseGregerror ("I was wrong ...")exceptGregerror as E:Print(e)#the __str__ method of the E object, which gets the return value

4.6 Assertions

# Assert Condition Print (123) assert 1==2# assertion print(456)

4.7 Single-Case mode

The purpose of the simple interest mode is to ensure that only a single instance exists in the current memory, avoiding memory waste.

for Python singleton mode, you can no longer use the object directly when you create it: obj = Foo (), and you should call a special method: obj = Foo.get_instance (). examples are as follows:

classFoo:__v=None @classmethoddefget_instance (CLS):ifAl1.__v:#if it has a value            returnAl1.__v        Else: CLS.__v=Foo ()returnAl1.__v#do not use Class () againObj=foo.get_instance ()#objects created by obj=Print(obj) obj2=foo.get_instance ()Print(obj2) obj3=foo.get_instance ()Print(OBJ3)#<__main__. Foo object at 0x000001b5a30e10f0>#<__main__. Foo object at 0x000001b5a30e10f0>#<__main__. Foo object at 0x000001b5a30e10f0>

Python Abstract: Object-oriented higher order

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.