Python's Path object-oriented advanced article

Source: Internet
Author: User

First, the field

Fields include: normal fields and static fields, they differ in definition and use, and the most essential difference is where the memory is stored in different places,

    • Normal field belongs to object
    • Static fields belong to class

Class Province:    # static field    country = ' China '    def __init__ (self, name):        # normal field        self.name = name# Direct access to normal field obj = Province (' Hebei province ') print obj.name# direct access to static fields Province.country

as can be seen from the code above, "Ordinary fields need to access the" static field through the class access, in the use can be seen in the normal field and static field attribution is different.

    • Static field saves only one copy in memory
    • Normal fields save one copy of each object

Scenario: When you create an object from a class, you use a static field if each object has the same field

second, the method

Methods include: Common methods, static methods, and class methods, three methods in memory belong to the class, the difference is that the calling method is different.

    • object "; at least one Span style= "color: #ff0000;" The self parameter, which automatically calls the method's object , when the normal method is executed self
    • call; at least one cls parameter; When you execute a class method, the class is copied to cls
    • static method: Called by ; no default parameters;
#方法的定义和使用class Foo:    def __init__ (self, name):        self.name = name    def ord_func (self): ""        defines the normal method, There is at least one self parameter "" "        # Print Self.name        print ' normal method '    @classmethod    def class_func (CLS):" "        defines the class method, There is at least one CLS parameter ""        Print class method '    @staticmethod    def static_func (): ""        defines a static method, no default parameter "" "        print ' static method ' # Call the normal method F = Foo () f.ord_func () # Call the class method Foo.class_func () # Call the static method Foo.static_func ()
Third, attribute

If you already know the methods in the Python class, the properties are very simple, because the properties in Python are actually variants of the common method .

For attributes, the following three points of knowledge are available:

    • Basic use of attributes
    • Two ways to define a property

1. Create Call Properties

# ############### definition ############## #class Foo:    def func (self):        Pass    # defines a property    @property    def prop ( Self):        pass# ############### call ############## #foo_obj = foo () foo_obj.func () Foo_obj.prop   #调用属性

the definition and invocation of a property is a few points to note:

    • When defining, add @property adorners on the basis of common methods;
    • When defined, the property has only one self parameter
    • When called, no parentheses are required
      Method: Foo_obj.func ()
      Property: Foo_obj.prop

Note: The attribute has the meaning that it can be used to create and access the exact same illusion of the field when accessing the property.

Property is a variant of the method, and if there are no attributes in Python, the method can completely replace its functionality.

Example: For the Host List page, each request is not possible to display all the contents of the database on the page, but by the function of paging to display locally, so when requesting data in the database to display the specified to obtain all the data from article M to Nth (that is: Limit m,n), this paging function includes:

      • Calculates M and n based on the current page and total number of data bars requested by the user
      • Request data from the database according to M and N

Class Pager:    def __init__ (self, current_page):        # User's current requested page number (first page, second page ...) )        self.current_page = current_page        # 10 data per page is displayed by default        self.per_items =    @property    def start (self):        val = (self.current_page-1) * Self.per_items        print (val)        return Val    @property    def end (self): C12/>val = self.current_page * Self.per_items        print (val)        return val# ############### call ############## #p = Pager (3) p.start# p.end# P.start is the starting value, namely: m# p.end   is the end value, namely: N

from the above, the function of the Python property is: A series of logical calculations inside the property, and finally the results are returned.

2. Two methods of defining attributes

There are two ways to define a property:

    • Adorners: Applying adorners on methods
    • Static fields are: A static word that defines a value as a Property object in a class

Adorner method

# ############### definition ############## #class Goods (object):    @property    def Price:        print ' @property '    @price. Setter    def price (self, value):        print ' @price. Setter '    @price. deleter    def-Price:        print ' @price. Deleter ' # ############### calls ############## #obj = Goods () Obj.price          # automatically executes @property decorated price method, and Gets the return value of the method Obj.price = 123    # automatically executes the @price. Setter-Modified price method, and  assigns 123 to the method's parameter del obj.price      # to automate @price. Delet Er-Modified Price method

since there are three kinds of access methods in the new class, we can define three methods for the same attribute according to the access characteristics of several properties: Get, modify, delete

Instance

Class Goods (object):    def __init__ (self):        # original price        self.original_price =        # discount        self.discount = 0.8    @property    def        Price: # Actual prices = Price * Discount        new_price = self.original_price * Self.discount        return n Ew_price    @price. Setter    def price (self, value):        self.original_price = value    @price. deltter    def price (self, value):        del self.original_priceobj = Goods () obj.price         # get commodity prices Obj.price = $   # Modified product Price del obj.price     # Delete original price

static Field method

There are four parameters in the property's construction method

    • The first parameter is the method name , which 对象.属性 automatically triggers the execution method when called
    • The second parameter is the method name , which 对象.属性 = XXX automatically triggers the execution method when called
    • The third parameter is the method name , which del 对象.属性 automatically triggers the execution method when called
    • The fourth parameter is a string that 对象.属性.__doc__ is called, and this parameter is the description of the property

Public members, accessible from anywhere

Private members, only inside the class can the method

Private members and public members are defined differently: the first two characters are underlined when a private member is named

For example:

Class C (object):    def __init__ (self):        self.name = ' public field '        Self.__foo = ' private field '

static fields

公有静态字段:类可以访问,类内部可以访问,派生类中可以访问;私有静态字段:仅类内部可以访问;

public class:

#!/usr/bin/env python3#coding:utf8class Person (object):    name = "Public Field property"    def __init__ (self):        Pass    def One (self):        print (Self.name) class child (person): def-one (self    ):        print (self.name) #类访问print (person.name) obj = person () #类的内部访问obj. One () ch = child () #子类可以访问ch.

Private fields

class Person (object):    __name = ' private field '    def __init__ (self):        pass    def one (self):        print (self.__name ) class Child:  def-i    :        print (Person.__name) #类访问print (person.__name)    error:    print (person.__name)    Ttributeerror:type object ' person ' have no attribute ' __name ' #类的内部访问obj = person () Obj.one () Result: Private field # subclass Access obj = Child () obj.t Wo () Error:    print (person.__name)    Attributeerror:type object ' person ' have no attribute ' _child__name '

Public common fields: objects can be accessed, accessible within classes, and accessible in derived classes

Private Normal field: Only within the class can be accessed;

* * ps:如果想要强制访问私有字段,可以通过 【对象._类名__私有字段明 】访问(如: Obj._c__foo), it is not recommended to force access to private members. **

public field Access:

class Person (object):    def __init__ (self):        self.name = ' Liu Yao '    def one (self):        print (Self.name) class Child: Def-one    :        print (self.name) obj = person () #通过类访问print (Obj.name) #通过内部访问obj. One () # Subclass Access OBJJ = Child () objj.two ()

Private class Access:

class Person (object):    def __init__ (self):        self.__name = ' Liu Yao '    def one (self):        print (Self.__name) class Child: Def-one    :        print (self.__name) obj = person () #通过类访问print (Obj.__name) #通过内部访问obj. One () # Subclass Access OBJJ = Child () objj.two ()

methods, properties are accessed in the same way that a private member can only be used inside a class

Iv. anomalies

1. Abnormal Foundation

Case:

NUM1 = input (' NUM1: ') num2 = input (' num2: ') Try:    num1 = Int (NUM1)    num2 = Int (num2)    result = Num1 + num2except Ex Ception as E:    print (e) #当我输入的都是数字的时候, not unusual # when I enter a non-numeric time to print the exception result: num1:1num2:minvalid literal for int () with base: ' m ‘

2. Abnormal type

1) Common 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 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 2) more exceptions Arithmeticerrorassertionerrorattributeerrorbaseexceptionbuffererrorbyteswarningdeprecationwarningenviron Menterroreoferrorexceptionfloatingpointerrorfuturewarninggeneratorexitimporterrorimportwarningindentationerrorindexerrori    Oerrorkeyboardinterruptkeyerror Lookuperrormemoryerrornameerrornotimplementederroroserroroverflowerrorpendingdeprecationwarningreferenceerrorruntimeerror Runtimewarningstandarderrorstopiterationsyntaxerrorsyntaxwarningsystemerrorsystemexittaberrortypeerrorunboundlocalerrorun IcodedecodeerrorunicodeencodeerrorunicodeerrorunicodetranslateerRorunicodewarninguserwarningvalueerrorwarningzerodivisionerror 

Case:

Indexerror

DIC = ["Liuyao", ']try:    dic[2]except indexerror as E:    print (e) #因为没有索引是2的打印异常list index out of range

Keyerror

DiC = {' K1 ': ' v1 ',}try:    dic[' K2 ']except keyerror as E:    print (e)

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) Result: invalid literal for int () with base: ' Hello '

3. Active departure anomaly

Try:    raise Exception (' wrong ... ') except Exception as E:    print (e) Result: wrong

4. Custom Exceptions

Class Liuyaoerror (Exception):    def __init__ (self, msg):        self.message = msg    def __str__ (self):        return Self.messagetry:    Raise Liuyaoerror (' my exception ') except Liuyaoerror as E:    print (e)

5. Assertion

# assert Condition assert 1 = = 1assert 1 = = 2
V. 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.

Class Foo (object):    def __init__ (self):        self.name = ' Liuyao '    def func:        return ' func '    def Niubi (self): return ' niubi ' obj = Foo () # # # # # # # # # # # # # # # # # # # # # # #        #a =hasattr (obj, ' name ') b=hasattr (. obj, ' func ') print (b) Result: True true if not present then false#### gets member # # #print (getattr (obj, ' name ')) print (GetAttr (obj, ' func ')) Result: Liuyao<bound Method Foo.func of <__main__. Foo object at 0x004db350>> if you want to get to and Execute method: print (GetAttr (obj, ' func ')) Result: My func##### set member # # # #setattr (obj, ' age ', SetAttr (obj, ' show ', Lambda Num:num + 1) print (GetAttr (obj, ' age ')) print (GetAttr (obj, ' Show ')) Results: 18<function < Lambda> at 0x004856a8># # # # # # # # # # # # # # # #delattr (obj, ' name ') # delattr (obj, ' func ') print (GetAttr (obj, ' name ')) Result: Because Self.name is already deleted in memory: print (getattr (obj, ' name ') Attributeerror: ' Foo ' object has no attribute ' name '

Python's Path object-oriented advanced 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.