Python object-oriented programming-basic concepts (python3.5)

Source: Internet
Author: User
Tags class definition

The brief generalization of object-oriented programming is to abstract the problem that will be handled into a collection of data and operations, encapsulating it with a class . Where data and operations are called properties of classes, they are generally invariant.

Instantiating a class generates the object that we call, and the object has its own properties. The properties of an object are generally personalized, and different objects may have different properties. All objects of the same class share the properties of the class.

Object properties are found in the following order: the object itself---class--Class ancestor class

All objects in Python.

Here we discuss class-related concepts and syntax in Python.

1. Definition of Class
class ClassName:         <statement-1> ...     <statement-N>
    • Class definition must use the class keyword
    • Class names are best used for large humps, such as ClassName, which is a convention
    • When the class definition is entered, a new namespace is generated, and all local variables defined in the class are put into this new namespace.
    • All variables in the namespace are properties of the class . Class properties are divided into two main categories, data attributes (variables) and functions.
    • After the statement block executes, a class object is generated to bind to the classname. The scope of the classname is determined by its defined position.

everything in Python is an object, and a class is an object, which is an instance of the type class. You can use obj.__class__ to see if an object is instantiated by that class.

Any valid statements can be used in a class, but in practice, it is primarily assignment statements and function definitions.

2. Class Objects

The following code defines a Chinese class:

classChinese:"""A Sample Example Class"""Nationality=' China'    defdisplay (self):Print(Self,'I am chinese! ', sep=', ') forName, valueinchSorted (Chinese.__dict__. Items (), key=Lambdax:x[0]):Print(Name,'==>', value)

The class definition generates a new namespace that contains all the variables defined locally in the class, that is, the properties of the class. These properties can be viewed in the __dict__ property of the class, and can be approximated to be equivalent to the namespace of the class. Where the __name__ form of the property is a special property.

Print(Type (Chinese.__dict__))#<class ' mappingproxy ' > forName, valueinchSorted (Chinese.__dict__. Items (), key=Lambdax:x[0]):Print(Name,'==>', value)#__dict__ ==> <attribute ' __dict__ ' of ' Chinese ' objects>#__doc__ ==> A Sample Example Class#__module__ ==> __main__#__weakref__ ==> <attribute ' __weakref__ ' of ' Chinese ' objects>#display ==> <function chinese.display at 0x1020759d8>#Nationality ==> China
    • __dict__ is automatically generated when the class is defined.
    • Automatically generated when the __doc__ class is defined. The value for the class defines the first line within the statement block, and the class's document string, referenced by three quotation marks. If there is no value of none.
    • The __module__ class defines the module in which the property is automatically added. If the module is being executed, the value is __main__
    • __weakref__
    • Display and nationality user-defined properties

The references to properties in Python are in the form of Obj.name , andname is the property of the object obj . All properties in a class can be referenced in the form of Obj.name . For example, two user-defined properties for this class: Data properties Nationality and function display:

Print (chinese.nationality)  #  China Print (Chinese.display)      # <function Chinese.display at 0x1021759d8> Chinese.display (1)          #  1, I am chinese! 

通过类引用函数并对其进行调用,与普通的函数调用没有差异。不过,在类中定义的函数一般是给实例使用的,不建议直接通过类引用,下面会进一步说明。

3. Instantiation of Class

The instantiation of a class uses a syntax similar to a function call.

XM = Chinese ()

The above statement creates an instance of the new Chinese class and assigns it to the XM variable. The instance has its own namespace:

Print (XM. __dict__)  #  {}

you can see that the return value of xm.__dict__ is an empty dictionary, and the instance XM does not have its own properties. You can add properties to an instance directly from the Xm.name = ' xiaoming ' form. You can also delete this property from Del Xm.name:

' xiaoming ' Print (XM. __dict__)      # {' name ': ' Xiaoming '} del Xm.name Print (XM. __dict__)      #  {}

If all instances of a class have certain properties, except that the value of the property is different, you can add properties to the instance in the method by defining the initialization method for the instance.

3.1 Initialization Method

The instantiation process of the class:

    1. Instantiate an Object
    2. Automatic invocation of special methods __init__ initialization of the resulting object. If there is no definition in the class, the method is found in the parent class (described after the concept of the parent class).

We call the __init__ method the initialization method of the instance.

Typically, the instance's personalization properties are defined in the instance initialization method, which is private to the instance and can be viewed through the __dict__ property of the instance. The properties of the instance do not affect the properties of the class, in other words the class cannot reference the properties of the instance.

The following is an extension to the Chinese class:

classChinese:"""A Sample Example Class"""Nationality=' China'    def __init__(self, name, age, gender): Self.name=name Self.age=Age Self.gender=Genderdefdisplay (self):Print(Self,'I am chinese! ', sep=', ')XM= Chinese ('xiaoming', 18,'male')Print(XM.__dict__)#{' name ': ' Xiaoming ', ' gender ': ' Male ', ' age ':Print(Chinese.__dict__. Keys ())#Dict_keys ([' __weakref__ ', ' __module__ ', ' __dict__ ', ' __init__ ', ' nationality ', ' display ', ' __doc__ '])

The self refers to an instance that references the method (specifically implemented in 4.1), and the parameter list of the instantiation operation is passed to the __init__ method, Chinese (' xiaoming ', ' Male ')--xm.__init__ (' xiaoming ', ' Male ')

3.2 Instances of Classes

To view the class of an object:

    • Obj.__class__
    • Type (obj)
Print (XM. __class__ )print(Type (XM))#  <class ' __main__. Chinese ' >#  <class ' __main__. Chinese ' >

determine if an object is an instance of a class: Isinstance (obj, ClassName)

Print (Isinstance (XM, Chinese)) # True
4 Example

Instances can manipulate two kinds of properties: Data Properties and methods

Print (Xm.name, Xm.age, Xm.gender, sep=")   # Xiaoming, male Print (Xm.nationality, Xm.display, sep=")    # China , <bound method Chinese.display of <__main__. Chinese object at 0x10217c898>>

With the code above you can see that the instance can reference not only its own properties, but also the properties of the class. A class property can be shared by its instance .

It is important to note that the instance references the function of the class. Its return value is not a function object but a method object that is bound by a "bound method" . Attempt to invoke this object:

  1  xm.display (1 2  #   Traceback (most recent Call last):  3  #   File" test.py ", line <module>  4  #   Xm.display (1)  5  #   Typeerror:display () takes 1 Positional argument but 2 were given   6  xm.display () #   <__main__. Chinese object at 0x10217c7f0>, I am chinese! 

The display function requires the passing of a positional parameter, the 1th line passes a parameter 1 to the method, the call error, and the error message tells us to pass in one more positional parameter.

Call again, do not pass the parameter, unexpectedly can call the normal! Why? function prints the value passed in, "<__main__. Chinese object at 0x10217c7f0> "indicates that a Chinese object is in and out of the box, in this case only XM. How is this going to be achieved?

4.1 Example methods
 Print(chinese.display)print(xm.display)print is Xm.display)#  <function chinese.display at 0x1021759d8>#  <bound Method Chinese.display of <__main__. Chinese object at 0x10217c7f0>>#  False 

The display property is referenced by classes and instances, respectively, and is not the same object returned: A function object is returned by a class reference, and a method object that is bound by a "bound method" is returned by an instance reference.

  • method: A function that belongs to an object . When a function object is referenced by an object (instance), the function and instance bindings return a method object. The corresponding instances and methods can be viewed through the __self__ and __func__ properties of the Method object
    method = xm.displayPrint(method).  __self__)      #  <__main__. Chinese object at 0x10217c7f0>print(method.  __func__)      #   <function chinese.display at 0x1021759d8>

  • The method object is callable, and the invocation of the method is its corresponding function call, except that its instance is passed to the function as the first argument, in the equivalent form: Method (*args, **kwargs) ==> method.__func__ (method.__ self__, **args, **kwargs). In this case, Xm.display () is equivalent to Chinese.display (XM).
  • A function defined in a class typically has at least one positional parameter, and the first positional parameter is typically identified with ' self ', referring to an instance of a reference function.
  • A function defined in a class corresponds to a method that is an instance of an instance. A function in a class is generally referenced by an instance, in order to describe a method in which we might refer directly to a function in a class.

Briefly, the first parameter of the method is populated automatically by Python to refer to the instance object .

The above is the basic concept, the next chapter discusses the encapsulation of classes, inheritance-related concepts.

Python object-oriented programming-basic concepts (python3.5)

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.