Python object-oriented-Advanced (class member, class member modifier)

Source: Internet
Author: User
Tags modifier

1. Members of the class

The members of a class can be divided into three main categories: fields, methods, and properties

Note: In all members, only the contents of the normal field are saved in the object, that is: how many objects are created based on this class, and how many normal fields are in memory. The other members are saved in the class,
That is, no matter how much the object is, only one copy is created in memory

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 through the object" "static field through 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

1, ordinary method: Called by the object , at least one self parameter, when the normal method is executed, the object that invokes the method is automatically assigned the value.
2, class method: Called by the class , at least one cls parameter; When the class method is executed, the class that invokes the method is automatically copied to the CLS;
3, static method: Called by the class , no default parameters;

Class Foo:    def __init__ (self, name):        self.name = name    def ord_func (self): ""        defines a normal method with at least one self parameter "" "        # print Self.name        print ' normal method '    @classmethod    def class_func (CLS): ""        defines a class method with at least one CLS parameter "" "        print ' class method '    @staticmethod    def static_func (): "" "        defines a static method, no default parameter" ""        print ' static method ' # call normal method F = Foo () F.ord_func () # Call the class method Foo.class_func () # Call the static method Foo.static_func ()

The same point: for all methods, all belong to the class (non-object), so in memory only one copy is saved
Different points: Different method callers, automatically passing arguments when calling a method

Third, attribute

The properties in Python are in fact a variant of the common method , which is basically used as follows:

# ############### definition ############## #class Foo:  def __init__ (self, name):        self.name = name    def func (self): C4/>pass    # defines a property    @property    def prop (self)        : print self.name# ############### call ############## #foo_obj = Foo (Kevin) Foo_obj.func () Foo_obj.prop   #调用属性, looks like the calling field

From the above, the function of the Python property is: A series of logical calculations inside the property, and eventually the results are returned

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 invocation: Foo_obj.func ()
Property invocation: Foo_obj.prop

One, two ways of attribute definition

1, the adorner is: Apply the adorner on the method
2. Static fields are: Static fields that define values as property objects in a class
Adorner mode: Apply @property adorner to ordinary method of class

Classic class with a @property adorner (example in the previous step)

New class with three kinds of @property adorners

# ############### 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

The properties in the new class are accessed in three ways and correspond to three @property, @ method names. Setter, @ Method name. Method of Deleter Modification
We can define three methods for the same attribute according to the access characteristics of several properties: Get, modify, delete

Static fields, creating static fields with values as Property objects

Classic and modern classes are no different when creating properties using static fields

Class Foo:    def get_bar (self):        return ' Wupeiqi '    bar = property (get_bar) obj = Foo () reuslt = obj. BAR        # Automatically calls the Get_bar method and gets the return value of the method print Reuslt

There are four parameters in the property's construction method:
The first parameter is the method name that invokes the object. The execution method is automatically triggered when the property is
The second parameter is the method name, which invokes the object. property = XXX automatically triggers the execution method
The third parameter is the method name, which invokes the Del object. The execution method is automatically triggered when the property
The fourth parameter is a string that invokes the object. property. __doc__, which is the description of the property

Class Foo:    def get_bar (self):        return ' Wupeiqi '    # * must have two parameters    def set_bar (self, value): Return         return ' Set value ' + Value    def del_bar (self):        return ' Wupeiqi '    bar = property (Get_bar, Set_bar, Del_bar, ' Description. ') obj = Foo () obj. BAR              # Automatically calls the method defined in the first parameter: Get_barobj. BAR = "Alex"     # automatically invokes the method defined in the second parameter: Set_bar method, and passes "Alex" as a parameter to del foo.bar          # automatically calls the method defined in the third parameter: Del_bar method obj. bae.__doc__      # automatically gets the value set in the fourth parameter: Description ...

Because there are three ways to create properties for static fields, we can define three methods for the same attribute based on the access characteristics of several of their properties: Get, modify, delete

Class Goods (object):    def __init__ (self):        # original price        self.original_price =        # discount        self.discount = 0.8    def get_price (self):        # actual price = Price * Discount        new_price = self.original_price * Self.discount        return new_price
   def Set_price (self, value):        Self.original_price = value    def del_price (self, value):        del Self.original_price    Prices = Property (Get_price, Set_price, Del_price, ' price attribute description ... ') obj = Goods () obj.         Price # Get commodity prices obj. Price = $   # modifies the original item del obj.     Price # Delete original item
2. Modifiers for class members

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. (except for special members, e.g. __init__, __call__, __dict__, etc.)

Private members and public members have different access restrictions:
Static fields
public static fields: classes are accessible, inside classes can be accessed, and in derived classes
private static field: Only the class can be accessed internally;

Class C:    name = "public static field"    def func:        print C.nameclass D (C):    def Show (self):        print C.namec.name         # class Access obj = C () obj.func ()     # class inside can access Obj_son = D () obj_son.show () # in derived classes you can access public static fields

Class C:    __name = "public static field"    def func:        print C.__nameclass D (C):    def Show (self):        print c.__ Namec.__name       # class access            ==> error obj = C () obj.func ()     # class inside can access     ==> correct Obj_son = D () obj_son.show () #   ==> Error private static fields can be accessed in derived classes

Normal field
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;

Class C:    def __init__ (self):        Self.foo = "public Field"    def func (self):        Print Self.foo # class internal Access Class D (C):    Def show (self):        the print Self.foo # derived class accesses obj = C () Obj.foo     # through the object access Obj.func ()  # class internal Access Obj_son = D (); obj_son.show ()  # Accessing public fields in derived classes

Class C:    def __init__ (self):        Self.__foo = "private Field"    def func (self):        Print Self.foo # class internal Access Class D (C): C13/>def Show (self):        the print Self.foo # derived class accesses obj = C () Obj.__foo     # through Object access    ==> error Obj.func ()  # class internal access        ==> Correct Obj_son = D (); Obj_son.show ()  # access  ==> error Private field in derived class

Note: If you want to force access to a private field, you can access it through the object. _ Class name __ Private character Deming (for example: Obj._c__foo), it is not recommended to force access to private members

Methods, properties are accessed in the same way that a private member can only be used inside a class
PS: If you want to access a private property, you can pass the object. _ Class __ Property name

Python object-oriented-Advanced (class member, class member modifier)

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.