Python basic 15 (object-oriented programming)

Source: Internet
Author: User
Tags class definition instance method

Although Python is an explanatory language, it is object-oriented and can be programmed with objects.

First, 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:        defines a class     ' Jack '        defines a property    def printname (self):    defines a method        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, Printname () is a method, and a function that binds to an object is called a method . 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.

Second, the attribute

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

1 class people: 2     ' Jack ' 3     Age =45 p = people ()6print 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.

1 class people: 2     __name ' Jack ' 3     __age =45 p = people ()6print 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.

Third, the method

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:

1 classpeople:2     __name='Jack'3     __age= 124 5     defGetName (self):#Define a method6         returnSelf.__name7     defgetage (self):8         returnSelf.__age9 Tenp =people () One PrintP.getname (), P.getage ()

Iv. 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

V. Class attributes, instance properties, class methods, instance methods, and static methods

First of all to talk about class properties and instance properties, in the previous example, we are exposed to the class property, as the name implies, the class property is the property of the class object , it is owned by the instance object of all class objects, there is only one copy in memory, for the common class properties, can be accessed from class objects and instance objects outside the class.

classPeople:name='Jack'  # public class Properties    __age= 12# Private Class PropertiesP=people ()PrintP.name# correctPrintPeople.name# correctPrintP.__age            # error, private class property cannot be accessed outside the class through an instance objectPrintPeople.__age       # error, private class property cannot be accessed outside the class through a class object

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

class people:     ' Jack '  ==12print p.name     correct print     p.age  correct print people.name     correct print     people.age  Error 

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.

classPeople:name='Jack'        #__init__ () is a built-in construction method that automatically calls when an object is instantiated    def __init__(self,age): Self.age=AGEP= People (12)PrintP.name# correctPrintP.age# correctPrintPeople.name# correctPrintPeople.age# Error

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.

classPeople:country=' China'    PrintPeople.countryp=people ()PrintP.countryp.country='Japan' PrintP.country# Instance Properties mask class properties with the same namePrintPeople.countrydelP.country# Delete Instance PropertiesPrintP.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:     '  China '         class method, decorated with Classmethod     @classmethod    def  Getcountry (CLS):         return  = people ()print p.getcountry ()    # can reference print using an instance object  people.getcountry ()    # can be referenced by a class object

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

classPeople:country=' China'        #class methods, decorated with Classmethod@classmethoddefGetcountry (CLS):returncls.country @classmethoddefsetcountry (cls,country): Cls.country=Country P=people ()PrintP.getcountry ()#Instance object reference can be usedPrintPeople.getcountry ()#can be referenced by a class objectP.setcountry ('Japan')   Printp.getcountry ()PrintPeople.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:     '  China '        # instance method    def getcountry (self):         return self.country         = people ()print p.getcountry ()         # correct, you can use an instance object to reference print People.getcountry ()    # error, cannot reference instance method through class object

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

class people:     '  China '         @staticmethod    # static method    def  getcountry ():         return people.country         Print

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 basic 15 (object-oriented programming)

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.