Python Object-oriented programming (i)

Source: Internet
Author: User
Tags instance method

Python Object-oriented programming (i)

Although Python is an explanatory language, it is object-oriented and can be programmed with objects. Here's a look at how to program object programming in Python.

I. How to define a class

Before you go into Python-oriented programming, learn several terms: classes, class objects, instance objects, properties, functions, and methods.

A class is a encapsulation of something in the real world, and defining a class can be defined in the following way:

Class ClassName:    block

Note that there is a colon behind the class name, and you can define the properties and methods within the block blocks. When a class is defined, a class object is created. The class object supports two operations: reference and instantiation. A reference operation invokes a property or method in a class through a class object, and instantiation is an instance of a class object called an instance object. For example, define a people class:

class people:    name = ' Jack '       #定义了一个属性    #定义了一个方法    def printname (self):        print Self.name

When the People class definition is complete, a global class object is created, and the properties and methods in the class can be accessed through the class object. The people in People.name is called a class object when accessed by People.name (as to why it can be accessed directly after the property, as long as the concept of the class object is understood), and differs from C + +. Of course, you can also instantiate the operation, P=people (), which produces a people instance object, you can also access the property or method through the instance object P (p.name).

After understanding the differences between classes, class objects, and instance objects, let's look at the differences between properties, methods, and functions in Python.

In the code above, it is clear that name is an attribute, and Printname () is a method that is called as a method of binding to an object. Functions that are typically defined within a class are bound to class objects or instance objects, so called as methods, and functions defined outside of the class are generally not bound to the object, called functions.

Two. Properties

In the class we can define some properties, such as:

class people:    name = ' Jack ' age    = 12p = People () print P.name,p.age

Defines a people class that defines the name and age attributes, with the default values of ' Jack ' and 12 respectively. After the class has been defined, it can be used to produce an instantiated object, the P = people () instantiation of an object p, and then the property can be read by P. The name and age are public and can be accessed directly outside the class by object name, and if you want to define it as private, you need to add 2 underscore ' __ ' to the front.

class people:    __name = ' Jack '    __age = 12p = People () print P.__name,p.__age

This program will run with error:

  

The property is not found because the private property cannot be accessed outside the class through the object name. In Python, there are no common and private keywords in C + + that distinguish between public and proprietary properties, which are distinguished by attribute naming, and if 2 underscore ' __ ' before the property name indicates that the property is a private property, otherwise public property (the same way, The method name is preceded by 2 underscores to indicate that the method is private, otherwise it is public.

Three. Methods

In a class, you can define methods as needed, define methods with the DEF keyword, a method defined in a class with at least one parameter, usually with a variable named ' self ' as the parameter (with a different name), and it needs to be the first argument. Let's look at an example:

class people:    __name = ' Jack '    __age =    def getName (self):        return self.__name    def getage (self):        Return SELF.__AGEP = people () print p.getname (), P.getage ()

  

If you don't understand self well, you can interpret it as the this pointer inside a C + + class, which is what the object itself means, and when you invoke the method with an object, you pass the object as the first argument to the.

Four. Methods built into the class

There are some built-in methods in Python, which have a special place for naming them (the method name starts with 2 underscores and ends with 2 underscores). The most common in class is the construction method and the destructor method.

Construction method __init__ (self,....) Called when the object is generated, can be used to do some initialization operations, do not need to display the call, the system will be executed by default. The construction method supports overloading, and the default construction method is automatically executed if the user does not redefine the constructor itself.

The Destructor method __del__ (self) is called when the object is disposed, supports overloading, and can be used to perform some operations that release resources, without the need to display calls.

There are some other built-in methods:

such as __cmp__ (), __len () __, and so on, the specific usage can refer to this blog post:

Http://www.cnblogs.com/simayixin/archive/2011/05/04/2036295.html

Five. Class properties, instance properties, class methods, instance methods, and static methods

After understanding the basics of the class, take a look at the differences between these concepts in Python.

Let's talk about class properties and instance properties.

In the previous example, we were exposed to the class attribute, as the name implies, the class property is the property owned by the class object, it is common to all class object's instance object, there is only one copy in memory, this is a bit similar to the static member variable of class in C + +. For common class properties, they can be accessed from class objects and instance objects outside the class.

class people:    name = ' Jack '  #公有的类属性    __age =     #私有的类属性p = people () print p.name             #正确print people.name        #正确print p.__age            #错误, private class properties cannot be accessed through instance objects outside the class print People.__age       #错误, private class properties cannot be accessed through class objects outside the class

Instance properties are not required to be defined in the class, such as:

class people:    name = ' Jack ' P = people () p.age =12print p.name    #正确print p.age     #正确print people.name    # Correct print people.age     #错误

After the class object people is instantiated outside the class, an instance object p is produced, and then P.age = 12 Adds an instance attribute of age to P, which is assigned a value of 12. This instance property is unique to the instance object P, noting that the class object people does not own it (so the age property cannot be accessed through the class object). Of course, you can also assign an age value when instantiating an object.

class people:    name = ' Jack '        #__init__ () is a built-in construction method that automatically calls    def __init__ (Self,age) When instantiating an object:        self.age = AGEP = people () print p.name    #正确print p.age     #正确print people.name    #正确print people.age     #错误

If you need to modify the class properties outside of the class, you must refer to the class object and then modify it. If a reference is made through an instance object, it produces an instance property of the same name, which modifies the instance property, does not affect the Class property, and then, if the property of that name is referenced by the instance object, the instance property forces the class property to be masked, that is, the instance property is referenced unless the instance property is deleted.

Class people:    country = ' China '    print People.countryp = people () Print p.countryp.country = ' Japan ' Print p.countr Y      #实例属性会屏蔽掉同名的类属性print people.countrydel p.country    #删除实例属性print p.country

  

  

Here's a look at the difference between a class method, an instance method, and a static method.

Class method: Is the method owned by the class object, it needs to use the decorator "@classmethod" to identify it as a class method, for a class method, the first parameter must be a class object, generally with "CLS" as the first parameter (of course, can use the other name of the variable as its first argument, but most people are accustomed to ' CLS ' As the first parameter's name, preferably with ' CLS ', can be accessed through instance objects and class objects.

Class people:    country = ' China '        #类方法, decorated with Classmethod    @classmethod    def getcountry (CLS):        return CLS.COUNTRYP = people () print p.getcountry ()    #可以用过实例对象引用print people.getcountry ()    #可以通过类对象引用

A class method can also be used to modify a class property:

Class people:    country = ' China '        #类方法, decorated with Classmethod    @classmethod    def getcountry (CLS):        return cls.country            @classmethod    def setcountry (cls,country):        cls.country = Country        p = people () Print p.getcountry ()    #可以用过实例对象引用print people.getcountry ()    #可以通过类对象引用p. Setcountry (' Japan ')   print P.getcountry ()   print people.getcountry ()    

Operation Result:

  

The results show that the access to the class object and the instance object has changed after the class method has been modified for the class property.

  

Instance method: A member method that is most commonly defined in a class that has at least one parameter and must have an instance object as its first argument, usually with a variable named ' self ' as the first parameter (of course, a variable of a different name as the first argument). An out-of-class instance method can only be called through an instance object and cannot be called by any other means.

Class people:    country = ' China '        #实例方法    def getcountry (self):        return self.country        p = people () print P.getcountry ()         #正确, you can reference the print people.getcountry () #错误 using an instance object    , and you cannot reference an instance method through a class object

Static methods: Modifiers need to be decorated with "@staticmethod", and static methods do not require multiple parameters.

Class people:    country = ' China '        @staticmethod    #静态方法    def getcountry ():        return People.country        Print people.getcountry ()     

For class and instance properties, if a property is referenced in a class method, the property must be a class property, and if a property is referenced in an instance method (unchanged), and a class property of the same name exists, the instance property masks the class property if the instance object has an instance property of the attribute, that is, the instance property is referenced. If the instance object does not have an instance property of that name, then the Class property is referenced, if a property is changed in an instance method, and if there is a class property of the same name, if the instance object has an instance property of the attribute, then the instance property is modified, and if the instance object does not have an instance property of that name, an instance property To modify a class property, if it is outside the class, it can be modified by the class object, and if inside the class, it is only modified in the class method.

From the definition of class and instance methods and static methods, it can be seen that the first parameter of a class method is the class object CLS, which must be the property and method of the class object that is referenced by the CLS, whereas the first argument of an instance method is the instance object self, which can be referred to by self as a class property, It may also be an instance property (which requires a specific analysis), but the instance property has a higher precedence in the case of class properties and instance properties with the same name. There is no need to define additional parameters in a static method, so referencing a class property in a static method must be referred to by the class object.

There are so many things about object-oriented programming, and other aspects of inheriting and method overloading of classes will continue to be explained later.

(GO) Python Object-oriented programming (i)

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.