Step Python3 (vi)--Object oriented

Source: Internet
Author: User
Tags uppercase letter

Python Object-oriented

What is object-oriented programming?

Object-oriented programming is a programming paradigm

Establishing an object model for the real world

Think of a program as a mutual invocation of different objects

Python has been an object-oriented language since its inception, which is why it is easy to create a class and object in Python. The following is a detailed introduction to Python's object-oriented programming.

If you have not been exposed to object-oriented programming languages before, you may need to first understand some of the basic features of object-oriented languages and form a basic object-oriented concept in your mind, which will help you learn more about Python's object-oriented programming.

Let's start with a brief look at some of the basic features of object-oriented.

Introduction to Object-oriented technology
    The
    • class: is used to describe a collection of objects that have the same properties and methods. It defines the properties and methods that are common to each object in the collection. An object is an instance of a class.
       defining classes and creating instances in Python, classes are defined by the class keyword. Take person as an example, define a person class as follows: Class (): Pass according to Python's programming habit, the class name begins with an uppercase letter, followed by (object), indicating which class the class inherits from. The inheritance of classes is explained in a later section, and now we simply inherit from the object class. With the definition of the person class, you can create concrete instances such as xiaoming, Xiaohong, and so on. Creating an instance is created using the class name + (), like a function call: Xiaoming = person () Xiaohong = person () 

        Note: Python 2 creates a class different from Python 3

After PY 2.2, the purpose of inheriting object is to make this class A new style class, without inheriting object for the classic classic class, tested in PY 2.7.11 >>> class A (object): ... pass ... >>> print (Type (A)) <type ' type ' >>>> class B (): ... >>> print (Type ( B) <type ' classobj ' ># visible 2 type is different >>> print dir (A) [' __class__ ', ' __delattr__ ', ' __dict__ ', ' __doc__ ', ' __format__ ', ' __getattribute__ ', ' __hash__ ', ' __init__ ', ' __module__ ', ' __new__ ', ' __reduce__ ', ' __reduce_ex__ ', ' __ Repr__ ', ' __setattr__ ', ' __sizeof__ ', ' __str__ ', ' __subclasshook__ ', ' __weakref__ ']>>> print dir (B) [' __doc__ ', ' __module__ ']# attribute is also different while Py 3.5.2:class A (object): Passprint (Type (a)) print (dir (a)) class B (): Passprint (Type (B)) PRI NT (dir (B)) <class ' type ' >[' __class__ ', ' __delattr__ ', ' __dict__ ', ' __dir__ ', ' __doc__ ', ' __eq__ ', ' __format__ ', ' __ge__ ', ' __getattribute__ ', ' __gt__ ', ' __hash__ ', ' __init__ ', ' __le__ ', ' __lt__ ', ' __module__ ', ' __ne__ ', ' __new__ ', ' _ _reduce__ ', ' __reduce_ex__ ', ' __repr__ ', ' __sEtattr__ ', ' __sizeof__ ', ' __str__ ', ' __subclasshook__ ', ' __weakref__ ']<class ' type ' >[' __class__ ', ' __delattr__ ' ', ' __dict__ ', ' __dir__ ', ' __doc__ ', ' __eq__ ', ' __format__ ', ' __ge__ ', ' __getattribute__ ', ' __gt__ ', ' __hash__ ', ' __init ' __ ', ' __le__ ', ' __lt__ ', ' __module__ ', ' __ne__ ', ' __new__ ', ' __reduce__ ', ' __reduce_ex__ ', ' __repr__ ', ' __setattr__ ', ' _  _sizeof__ ', ' __str__ ', ' __subclasshook__ ', ' __weakref__ '] illustrates that the PY 3.5 object has been inherited as the default base class (as in Java).
    • field : . , class .
      class Province: # static field country = ' China ' def __init__ (self, name): # PU Pass field self.name = name# Direct access to normal field obj = Province (' Hebei province ') print (obj.name) # Direct Access static field print (Province.country) 

       < Span style= "FONT-SIZE:13PX;" The static field saves only one copy of in memory,

    • method : belongs to the class in memory, except that it is called differently.

                  general method: Called by the object , at least one self parameter; When you execute a normal method, the object that calls the method is automatically assigned a value of "
     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;
    static method: called by the class; no default argument;

#!/usr/bin/env python# Version = 3.5.2# __auth__ = ' Nameless Little Demon ' class Foo:    def __init__ (self, name):        self.name = name
   
    def Ord_func (self): "" "        defines the normal method, with at least one self parameter" ""        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 with no default parameter "" "        print (' static method ') # Call the normal method F = Foo (' Then ') F.ord_func () # Call the class method Foo.class_func () # Call the static method Foo.static_func ()
   

Try not to execute static methods and class methods with objects.

   Properties:   the properties in Python are actually variants of the common method .

Class Foo:    def func (self):        pass    # definition attribute    @property    def prop (self):        print (' xxx ') # ############ # # # 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 is possible to create an illusion that the field is exactly the same when accessing the property .

There are two ways to define a property:
    • Adorners: Applying adorners on methods
    • Static fields are: Static fields that define values as property objects in a class

Adorner mode: apply @property Adorner to ordinary method of class

#!/usr/bin/env python# Version = 3.5.2# __auth__ = ' Nameless Little Demon ' class Pager ():    def __init__ (self,all_count):        Self.all_ Count = All_count    @property    def all_pager (self):        a1,a2 = Divmod (self.all_count,10)        if a2 = = 0:            x = A1        Else:            x = a1 + 1        return x    @all_pager. Setter    def all_pager (self,value):        Self.all_count = Value *    @all_pager. Deleter    def all_pager (self):        print (' deleter ') P = pager (101) print (P.all_pager) P.all_pager = 123print (p.all_pager) del P.all_pager

Output Result:

11123deleter

static fields, creating static fields with values as Property objects

    • method Name , called object. automatically triggers execution when
    • method name , which calls object. property = XXX automatically triggers the execution method
    • The third parameter is , called del object. Properties automatically triggers the execution method
Class Foo:    def get_bar (self):        return ' xiaoyao1 '    # * must have two parameters    def set_bar (self, value):        print (' Set Value is ' + value]    def del_bar (self):        print (' Xiaoyao2 ')    Bar = Property (Fget=get_bar, Fset=set_bar, fdel= Del_bar) obj = Foo () obj. BAR              # Automatically calls the method defined in the first parameter: Get_barx = obj. Barprint (x) obj. BAR = "Alex"     # automatically invokes the method defined in the second parameter: Set_bar method and Passes "Alex" as a parameter to Del obj. BAR          # Automatically calls the method defined in the third parameter: Del_bar method Xiaoyao1set value is Alexxiaoyao2


    • inheritance: A derived class (derived class) that inherits the fields and methods of the base class. Inheritance also allows the object of a derived class to be treated as a base class object. For example, there is a design where an object of type dog is derived from the animal class, which is the analog "is a (is-a)" Relationship (example, dog is a animal).
    • instantiation: Creates an instance of a class, the concrete object of the class.
    • method: a function defined in a class.
    • object: An instance of a data structure defined by a class. The object consists of two data members (class variables and instance variables) and methods.

Step Python3 (vi)--Object oriented

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.