Python Learning Notes-(11) Object-oriented advanced & exception handling

Source: Internet
Author: User

In the previous article we have learned some basic object-oriented knowledge, this time to understand some of the object-oriented advanced knowledge (although I do not know what the egg used).

Static methods

A static method is a normal function that is in the namespace defined by the class and does not operate on any instance type. Use the adorner @staticmethod to define a static method. Both class objects and instances can call static methods ;

Said so much, it will be some crazy, we still directly on the code to see how to use the static method!

1. Write the code according to normal logic and add @staticmethod to define the static method eat:

class people (object):    def __init__ (self,name):        self.name = name     @staticmethod #把eat方法变为静态方法    def Eat ( Self):        print ("%s is eating"% self.name) d = people ("CC") D.eat ()

Running the above code, we will find the following error reported:

Typeerror:eat () Missing 1 required positional argument: ' Self'

----------eat requires a self parameter, but is not passed when it is called

So ... We can conclude that eat becomes a static method and does not automatically pass the instance itself as a parameter to self when invoked through an instance.

2. Workaround:

1) When invoking the instance itself to the Eat method, i.e. D.eat (d)

class people (object):    def __init__ (self, name):        self.name = name    @staticmethod  # Turn the Eat method into a static method    Def eat (self): print        ("%s is eating"% self.name) d = people ("CC") D.eat (d) #------printout------#cc is eating

2) Remove the self parameter in the Eat method (this also means that you cannot pass self in the eat. Calling other variables in the instance)

class people (object):    def __init__ (self, name):        self.name = name    @staticmethod  # Turn the Eat method into a static method    Def eat (): Print        ("%s is eating"% self.name) d = people ("CC") D.eat () #------------------print out----------------#print ( "%s is eating"% self.name) #NameError: The name ' self ' was not defined

Class method

A class method is a way to manipulate the class itself as an object. The class method uses the @classmethod adorner definition, whose first argument is a class, and the contract is written as a CLS. class objects and instances can call class methods.

The difference between a class method and a normal method is that a class method can only access a class variable and cannot access an instance variable.

Still the original code, the eat into a class method to see:

class people (object):    def __init__ (self, name):        self.name = name    @classmethod  # Turn the Eat method into a class method    def Eat (self): print        ("%s is eating"% self.name) d = people ("CC") D.eat ()---------------printout-------------------Printing (" %s is eating "% self.name) Attributeerror:type object ' People ' have no attribute ' name '

Error description: People no name attribute;

As mentioned above, the class method can only access the class variable, cannot access the instance variable, and name here is the instance variable.

Let's add a class variable to try it out:

class people (object):    name = "Class variable"    def __init__ (self, name):        self.name = name    @classmethod  # Turn the Eat method into a class method    Def eat (self):        print ("%s is eating"% self.name) d = people ("CC") d.eat ()-------------------- Print output-------------------class variable is eating

Property method

The function of the attribute method is to change a method into a static property by @property;

Still the previous code, the Eat method into a static property to see the effect:

class people (object):    name = "Please call me class variable"    def __init__ (self, name):        self.name = name    @property  # Turn the Eat method into a static property    Def eat (self):        print ("%s is eating"% self.name) d = people ("CC") d.eat ()----------------- Print output--------------------    d.eat () TypeError: ' Nonetype ' object is not callable

The error here is because eat has become a static method, of course, can not be used () to call, we directly call to try:

D.eat-------------Print output------------cc is eating

Reflection

1. Definition of Reflection

To manipulate members in an object as a string

    • To look for a member in an object as a string
    • To set a member in an object as a string
    • Remove a member from an object as a string
    • To determine whether a member exists in an object based on the form of a string
2. Function of Reflection
    • GetAttr (object, name[, default])

To look for a member in an object as a string

class people (object):    def __init__ (self):        self.name = ' cc '    def eat (self):        return ' HI ' d = people () Ret1 = GetAttr (d, ' eat ') Ret2 = GetAttr (d, ' name ') r1 = Ret1 () print (R1) print (Ret2)--------------printout----------------HICC
    • SetAttr (object, name, value)

To set a member in an object as a string

class people (object):    def __init__ (self):        self.name = ' cc '    def eat (self):        return ' HI ' d = people () Set1 = SetAttr (d, ' age ', +) R1 = GetAttr (d, ' age ') print (r1)-----------------------PrintOut---------------------------18
    • Delattr (object, name)

Remove a member from an object as a string

class people (object):    def __init__ (self):        self.name = ' cc '    def eat (self):        return ' HI ' d = people () Del1 = Delattr (d, ' name ') r1 = getattr (d, ' name ') print (r1)----------------printout-------------------attributeerror: ' People ' object has no attribute ' name '
    • Hasattr (object, name)

To determine whether a member exists in an object based on the form of a string

class people (object):    def __init__ (self):        self.name = ' cc '    def eat (self):        return ' HI ' d = people () H1 = Hasattr (d, ' age ') H2 = hasattr (d, ' name ') print (H1,H2)---------------printout-----------------False True

Exception handling

In the course of the previous study we will be exposed to a variety of error messages, programming process in order to increase the friendliness of the corresponding errors can be captured and give a hint message.

Common exceptions:

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

More Exceptions:

Arithmeticerrorassertionerrorattributeerrorbaseexceptionbuffererrorbyteswarningdeprecationwarningenvironmenterroreoferror Exceptionfloatingpointerrorfuturewarninggeneratorexitimporterrorimportwarningindentationerrorindexerrorioerrorkeyboardint Erruptkeyerrorlookuperrormemoryerrornameerrornotimplementederroroserroroverflowerrorpendingdeprecationwarningreferenceerr Orruntimeerrorruntimewarningstandarderrorstopiterationsyntaxerrorsyntaxwarningsystemerrorsystemexittaberrortypeerrorunbou Ndlocalerrorunicodedecodeerrorunicodeencodeerrorunicodeerrorunicodetranslateerrorunicodewarninguserwarningvalueerrorwarni Ngzerodivisionerror

Common Exception Instances:

Indexerror (output specifies error messages and prints error messages)

DIC = [1,2]try:    dic[2]except indexerror as E:    print ("I got it! \ n ", e)---------------------------print output--------------------------I got it! List index out of range

Keyerror (output specifies error messages and prints error messages)

DIC = {' name ': ' CC '}try:    dic[' age ']except Keyerror as E:    print ("I got it! \ n ", e)---------------------------print output---------------------------I got it! ' Age '

ValueError

S1 = ' Hello ' try:    int (s1) except ValueError as E:    print (e)--------------------------- Print output----------------------------invalid literal for int. () with base: ' Hello '

Universal Exception Exception: (not recommended, not easy to debug; can be used in conjunction with the exception)

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

Custom Exceptions:

Class Ccexception (Exception):    def __init__ (self,msg):        self.msg = msg    def __str__ (self):        return Self.msgtry:    Raise Ccexception ("my exception") except Ccexception as E:    print (e) 

Python Learning Notes-(11) Object-oriented advanced & exception handling

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.