Python object-Oriented Programming summary (top)

Source: Internet
Author: User
Tags instance method

Before I learned Python, I thought Python was a scripting language and couldn't be programmed with the method of a face object, and when I learned Python I found I was wrong, Python not only supports the faces but also uses a lot of people. I started from the touch programming is the Java language learning, so the idea of face object programming in my mind is deeply rooted, let me a bit from object-oriented programming to process-oriented programming and some do not adapt, so I will summarize the Python object-oriented programming methods and procedures. I will analyze according to the object-oriented constituent elements, in order class and instance, property, method, encapsulation, inheritance, polymorphism , if there is any problem also please point out that I use the version of python2.7!

I. Classes and instances

Object-oriented is a programming idea that maps real-life things into the world of programs, so we can use real-life thinking to consider programming problems, which makes programming easier, after all we've lived in real life for decades.

Let's take a look at the basic forms of classes in Python.

class Movie(object):    def __init__(self,name,length):        self.name = name        self.length = length    def print_name(self):        print‘电影的名称是:%s‘ % (self.name,)

Class Movie: Is a fixed notation, class indicates that a class is being declared, the Movie is a class name, (object) is inherited from those parents, just like Java, all classes are inherited from the object class, So if you write a class that does not inherit from other classes, it is written as inheriting from object, and when inherited from object, the parentheses, together with the object in parentheses, can be omitted as: Class Movie:

The first method __init__ is to construct the method, the first parameter of the constructor is always self, the object of the class itself, when the object is actually constructed, the parameter does not have to be written, the Python compiler will add itself, the function of the constructor is to assign a value to the Assign the name and length of the movie to self as above.

For the above movie class we can call it with the following code:

import OOPmovie = OOP.Movie(‘大圣归来‘,90)movie.print_name()

The result of the output is: the name of the movie is: The Return of the sage

If you do not need to pass any parameters to the object, then the construction method can be omitted, for example:

class Movie(object):    def print_info(self):        print‘这是一个电影的类‘

This allows you to construct an object without passing any parameters such as:

import OOPmovie = OOP.Movie()movie.print_info()

The result of the output is: This is a movie class

Second, the attribute

1. Instance Properties

Instance properties are owned by objects, each object has its own set of properties, and instance properties between different objects do not interfere with each other. In Python, the __init__ attribute declared in a method is an instance property. Of course, you can also declare instance properties in any of the methods in the class using self.var=something, but I personally think this will make the program very confusing and error prone, as shown in this example:

Opp

# -*- coding: utf-8 -*-class Movie(object):    def __init__(self,name,length):        self.name = name        self.length = length    def print_name(self):        ‘123‘        print‘电影的名称是:%s‘ % (self.name,)

Ooptest

# -*- coding: utf-8 -*-import OOPmovie1 = OOP.Movie(‘大圣归来‘,90)movie2 = OOP.Movie(‘美人鱼‘,120)print movie1.nameprint movie2.namemovie1.print_name()print#只有在调用了print_name方法之后,aa才会被定义movie1.name=‘风声‘print movie1.nameprint#movie1的改变并未影响到movie2

Output Result:
The return of the sage
Mermaid
The name of the film is: The Return of the sage
123
Wind
Mermaid

2. Class Properties

Class attributes are owned by this class, and all instances share a variable, and if an instance changes the value of a class property, all instances are affected. The declaration of a class property is independent of all methods and is declared as follows:

Oop

#-*-coding:utf-8-*- class  movie  :  count = 1   #类属性  def  __init__      (self,name,length) :  self.name = name self.length = length def  print_name  Span class= "Hljs-params" (self) :  self.aaa =  ' 123 '  print  % (Self.name,)  

The above count is a class property, and the class property is similar to the static variable in Java. You can call by using the class name, count, or by instance. Count, which is commonly used to count objects, or to share variables between different instances, see the example below to understand class variables.

#-*-Coding:utf-8-*-Import OOPmovie1 = OOP. Movie (' The return of the Holy Sage ', -) Movie2 = OOP. Movie (' Mermaid ', -) Print OOP. Movie.Count #1 called by the class name. CountPrint Movie2.Count #1 called by instance. CountMovie1.Count=3Print OOP. Movie.Count #1Print Movie1.Count #3Print Movie2.Count #1Oop. Movie.Count=3Print OOP. Movie.Count #3Print Movie1.Count #3Print Movie2.Count #3

The results of the output are shown in the comments, and we can see that if the call is made using the class name. Count, then all the values in the instance will be changed, but if the call is made by instance. Count, then only the corresponding instance value has changed.

Third, the method

Python's methods do not differentiate static and instance methods as strictly as C#,java these compiled languages. This means that Python's static methods, class methods, and instance methods differ only on the invocation, and both types and instances can be called.

1. Example Method

An instance method can be called by a class instance, and is called through an instance. method, which we are not unfamiliar with, the Print_name method in the above example is the instance method, the use of the instance method is the argument method declaration when the parameter is passed one less, because the first parameter self is not provided. In addition, the instance method can be called by the class, in the form of the class name. Method Name (self), you must manually add the self variable, which is an instance of the class.

2. Class Methods

Class methods can be called by classes and class instances, but class methods cannot access instance variables, only methods can access class variables, declarations are preceded by @classmethod, and the first parameter in the method is CLS and not self, as with instance methods. When used, the first parameter is not passed, and the Python compiler automatically adds it. The class method is more like the static method in Java.

3. Static method

Static methods can be called by classes and class instances, cannot access instance variables and class variables, can only be passed in parameters, declared when the method is preceded by a @staticmethod, static methods do not have default parameters, static methods are a bit like the function of the tool library.

Oop

#-*-Coding:utf-8-*- class Movie(object):Count =1     def __init__(self,name,length):Self.name = Name Self.length = length#实例方法     def print_name(self):SELF.AAA =' 123 '        Print ' The name of the movie is:%s '% (Self.name,)#类方法    @classmethod     def print_len(CLS):        Print ' The length of the movie is:%d '% (Cls.count,)#静态方法    @staticmethod     def print_info(str):        Print ' The incoming message is:%s '% (str,)

Ooptest

# -*- coding: utf-8 -*-import OOPmovie1 = OOP.Movie(‘大圣归来‘,90#通过实例调用实例方法#如果通过类调用实例方法,必须手动传入实例#通过类调用类方法#通过实例调用类方法OOP.Movie.print_info(‘哈哈‘#通过类调用静态方法movie1.print_info(‘哈哈‘#通过实例调用静态方法

There are many remaining, one at a time to write, the next in the discussion of encapsulation, inheritance and polymorphism, thank you for your support!

Python object-Oriented Programming summary (top)

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.