Python Object-oriented programming (i)

Source: Internet
Author: User
Tags class definition instance method

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:    'Jack'       #defprint 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:    'Jack' age =p = people ()print p.name,p.age    
Return Result: Jack 12

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    
Operation result Error: Traceback (most recent):  ' E:\PYTHON\Eclipse\eclipse\Doc\day1\demo.py in<module >    print P.__name,p.__age'__name'        

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:

#Coding:utf8class people:    'Jackdefreturn self.  defreturn self.  __agep = people ()print p.getname (), P.getage ()         
Running Result: Jack 12

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.

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.

#Coding:utf8class People:name =  "jack "#  public class Property __age = # Private class Property p = people () print p.name # correct print people.name # correct Span style= "COLOR: #008000" >#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      
Run result Jackjack

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

#Coding:utf8class people:    'Jack'p = people () p.age =12# correct #  Correct # correct #print people.age #错误          
Running result: jack12Jack

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.

#Coding:utf8Class People:name =  ' jack ' #__init__ () is a built-in construction method, Automatically call def __init__ AGEP = People (12) print p.name # correct # correct print People.name # correct #print people.age #错误           
Running result: jack12Jack

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.

#Coding:utf8class People:country = china "print People.countryp = people () print P.countryp.country =  ' japan ' print p.country # instance properties will mask class properties with the same name print people.country< Span style= "COLOR: #0000ff" >del p.country # Delete instance Properties print p.country           
Running Result: Chinachinajapanchinachina

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.

 #coding:utf8class< Span style= "COLOR: #000000" > People:country =  ' china ' # @classmethod def Getcountry (CLS) : return Cls.countryp = People () print p.getcountry () # print people.getcountry () # can be referenced by a class object         
Running Result: Chinachina

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

Code
Running Result: Chinachinajapanjapan

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.

 #coding:utf8class< Span style= "COLOR: #000000" > People:country =  ' china ' # instance method def Getcountry (self):  Return Self.country p = people () print p.getcountry () # right, You can use an Instance object reference print people.getcountry () # error, cannot reference instance method through class object             
Run Result: Chinatraceback (most recent call last):  "E:\demo.pyin <module>    # Error, Instance methods cannot be referenced by class object Typeerror:unbound method Getcountry () must is called with people instance as first argument (got nothing ins Tead)    

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

#Coding:utf8class people:    'China'#defreturnprint People.getcountry ()         

Operation Result:

China

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.

Python Object-oriented programming (i)

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.