Object-oriented and related

Source: Internet
Author: User
Tags for in range

One, isinstance (obj, CLS)

Checks if obj is an object of class CLS

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

Second, Issubclass (sub, super)

Check if the sub class is a derived class of super class

Class Bar ():    passclass foo (Bar):    passobj = foo () ret = isinstance (obj,foo) Ret1 = Issubclass (foo,bar) Ret3 = Isinstance (Obj,bar) print (ret) #Trueprint (RET1) #True
Print (RET3) #True

Third, exception handling

1. Abnormal Foundation

In the programming process in order to increase the friendliness of the program in the event of a bug will not be displayed to the user error message, but the reality of a hint of the page, popular is not to let users see the big Yellow Pages!!!

Try:    passexcept exception,ex:    Pass

Requirement: Add two numbers entered by the user

 whileTrue:num1= Raw_input ('NUM1:') num2= Raw_input ('num2:')    Try: Num1=Int (NUM1) num2=Int (num2) result= Num1 +num2exceptException, E:Print 'An exception occurred with the following information:'        PrintE
View Code

2. Abnormal type

There are so many exceptions in Python that each exception is dedicated to handling an exception!!!

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 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
Common Exceptions
Arithmeticerrorassertionerrorattributeerrorbaseexceptionbuffererrorbyteswarningdeprecationwarningenvironmenterroreoferror Exceptionfloatingpointerrorfuturewarninggeneratorexitimporterrorimportwarningindentationerrorindexerrorioerrorkeyboardint Erruptkeyerrorlookuperrormemoryerrornameerrornotimplementederroroserroroverflowerrorpendingdeprecationwarningreferenceerr Orruntimeerrorruntimewarningstandarderrorstopiterationsyntaxerrorsyntaxwarningsystemerrorsystemexittaberrortypeerrorunbou Ndlocalerrorunicodedecodeerrorunicodeencodeerrorunicodeerrorunicodetranslateerrorunicodewarninguserwarningvalueerrorwarni Ngzerodivisionerror
more ExceptionsExample: Indexerror

DIC = {'K1':'v1'}try:    dic[ ' K20 ' ]except  keyerror, E:    print E
Example: Keyerror
' Hello ' Try :    int (s1)except  valueerror, E:    print E
Example: ValueError

For the above instance, the exception class can only be used to handle the specified exception condition and cannot be processed if the unspecified exception is not specified.

# uncaught exception, program direct error S1 = ' Hello ' try:    int (s1) except Indexerror,e:    print E

So, write a program that takes into account any exceptions that might occur in a try code block, which you can write:

S1 ='Hello'Try: Int (s1)exceptIndexerror as E:Print(e)exceptKeyerror as E:Print(e)exceptValueError as E:Print(e)exceptTypeError as E:Print(e)#OutputInvalid literal forInt () with base 10:'Hello'

Universal exception in Python's exception, there is a universal exception: Exception, he can catch arbitrary exceptions, namely:

S1 = ' Hello ' try:    int (s1) except Exception as E:    print (e) #输出invalid literal for int. () with base: ' Hello '

Next you may ask, since there is this universal exception, the other exception is not can be ignored!

A: Of course not, exceptions for special handling or reminders need to be defined first, and finally defined exception to ensure that the program runs correctly.

S1 = ' Hello ' try:    int (s1) except Keyerror as E:    print (' key error ') except Indexerror as E:    print (' index error ') except Exception as E:    print (' ERROR ')
# #输出
Error

3, abnormal other structure

Try:    # main code block    passexcept keyerror,e:    # Exception when executing the block    passelse:    # The main code block executes, executes the block    passfinally:    # Whether abnormal or not, the final execution of the block    Pass

4. Active Trigger Exception

Try:    raise Exception (' Error ... ') except Exception as E:    print (e) #输出错误 ...

5. Custom Exceptions

Class Jasonexceiption (Exception):    def __init__ (self,msg):        self.message = msg    def __str__ (self):        return Self.messagetry:    raise Jasonexceiption (' Jason Exception ') except Jasonexceiption as E:    print (E ) #输出Jason Exception

6. Assertion

Assert statement, if not mistaken, this thing in C or C + + also have. is a short assertion. The following is a description from the Python Help document:

Assert statements is a convenient-to-insert debugging assertions into a program:

An Assert statement is a convenient way to insert a debug breakpoint into a program

Use format for ASSERT statements

Assert expression

This statement is equivalent to the following sentence:

If __debug__:    if not expression:raise assertionerror

Assert can also be used for assertions of multiple expressions

Assert expression1, expression2

I wrote it myself. An example of assert usage for prime number determination

def IsPrime (n):     """ This function return a number was a prime or not """    assert N >= 2 from    import  sqrt     for in range (2, int (sqrt (n)) +1):         if n% i = = 0            :return     Falsereturn True
IsPrime (0)
# #输出

Assert N >= 2
Assertionerror

Four. Python's super usage

Original address: http://www.cnblogs.com/herbert/archive/2011/09/29/2195219.html

Super is used to solve multiple inheritance problems, it is not a problem to call the parent class directly with the class name when using single inheritance, but if multiple inheritance is used, it involves various problems such as lookup order (MRO), repeated invocation (Diamond inheritance). In short, the experience left behind is: to maintain consistency. Either call the parent class with the class name, or use Super, not half.

Common inheritance

Class Fooparent (object):    def __init__ (self):        self.parent = ' i\ ' the parent. '        Print (' parent ')    def Bar (self,message):        print (message, ' from Parent ') class Foochild (fooparent):    def __ Init__ (self):        fooparent.__init__ (self)        print ("Child")    def Bar (self,message):        Fooparent.bar (self , message)        print (' Child bar function. ')        Print (self.parent) if __name__== ' __main__ ':    foochild = Foochild ()    foochild.bar (' HelloWorld ')
#输出

Parent
Child
HelloWorld from Parent
Child bar function.
I ' m the parent.

Super inheritance

Class Fooparent (object):    def __init__ (self):        self.parent = ' i\ ' the parent. '        Print (' parent ')    def Bar (self,message):        print (message, ' from Parent ') class Foochild (fooparent):    def __ Init__ (self):        super (Foochild,self), __init__ ()        print (' child ')    def Bar (self,message):        Super ( Foochild, self). Bar (message)        print (' Child Bar fuction ')        print (self.parent) if __name__ = = ' __main__ ':    Foochild = Foochild ()    foochild.bar (' HelloWorld ')
#输出

Parent
Child
HelloWorld from Parent
Child bar function.
I ' m the parent.

From the running results, normal inheritance and super inheritance are the same. But in fact, their internal operating mechanism is different, this is reflected in the multiple inheritance is obvious. In the super mechanism, the public parent class is guaranteed to be executed only once, and the order of execution is in accordance with MRO (E.__MRO__).
Note: Super inheritance can only be used in modern classes, and will be an error when used in classic classes.
New class: Must have an inherited class, if there is nothing to inherit, then inherit object
Classic class: There is no parent class, and if you call super at this point there will be an error: "Super () Argument 1 must is type, not Classobj"

For a more detailed reference

http://blog.csdn.net/johnsonguo/article/details/585193

Summarize
1. Super is not a function, it is a class name, like Super (B, self) actually called the Super class initialization function,
produced a Super object;
2. The Super class initialization function does not do anything special, but simply records the class type and the concrete instance;
3. Super (B, self). The invocation of Func is not a Func function that invokes the parent class of the current class;
4. Python's multi-inheritance class ensures that functions of each parent class are called through the MRO method, and that each parent class function
Call only once (if each class uses Super);
5. Mixing super and unbound functions is a risky behavior, which can cause the parent class function that should be called to not call or a
A parent class function is called multiple times.

Five. Ordered dictionaries

classmydict (dict):def __init__(self): Self.li=[] Super (mydict,self).__init__()    def __setitem__(self, Key, value): Self.li.append (key) Super (mydict,self).__setitem__(Key,value)def __str__(self): temp_list= []         forKeyinchSelf.li:value=self.get (Key) Temp_list.append ("'%s ':%s"%(key,value)) Temp_str="{"+",". Join (Temp_list) +"}"        returnTemp_strobj=mydict () obj['K1'] = 123obj['K2'] = 456Print(obj)
View Code

Six, the design mode of the single case mode

Pattern Feature: guarantees that the class has only one instance and provides a global access point to access it.

Note: In order to achieve a single model cost a lot of work, and later found a blog post on this has a very detailed introduction, and the way of implementation is also very rich, through the code to learn more about the use of Python. The following code is from Ghostfromheaven's column, Address: http://blog.csdn.net/ghostfromheaven/article/details/7671853. But as its author in the Python single-mode Ultimate Edition says:

Class Foo:    instance = None    def __init__ (self,name):        self.name = name    @classmethod    def get_ Instance (CLS):        #cls类名        if cls.instance:            return cls.instance        else:            obj = CLS (' Alex ')            cls.instance = obj            return obj    def __str__ (self):        return self.nameobj1 = Foo.get_instance () print (OBJ1) Obj2 = Foo.get_instance () print (obj2) obj = Foo (' Jason ') print (obj)

Object-oriented and related

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.