Python3.5-- object-oriented programming


1 Comparison of process-oriented and object-oriented

(1) Process-oriented programming (procedural programming)

Process-oriented programming is also known as: top-down languages, step by step implementation of the program from top to bottom, from beginning to end solution to the problem.

The basic design ideas are: a start program is to solve a big problem, and then break down big problems into small problems or sub-processes, when these small problems continue execution of decomposition,

Until small problems are simple enough to be solved within a small range.

Disadvantages: If the program to be modified, the modified portion of each dependent should also be amended so that the impact of the series will take place, as the program increases, the difficulty of maintaining the programming mode will be higher.

So, if you write about simple script to do some one-time task, with a process-oriented approach is excellent, if you want to handle the task is complex and requires constant iteration and maintenance, or object-oriented is the most convenient.

(2) object-oriented programming (OOP)

Object-oriented programming is the use of "class" and "object" to create a variety of models to achieve a description of the real world.

Advantage: the maintenance and expansion program becomes simple, and can greatly improve the efficiency of the development process; Also, object-based programming, so that others can better understand your code logic, team development is becoming more calm.

Core features: world things are objects, everything in the world Jieke classification.

a、类(class)

Classes: a class is an abstract object have the same attribute, the blueprint, the prototype. These objects are defined in the class have the attributes, the common method.

b, the object (object)

Object: to instantiate the instance of a class, a class must be instantiated in the program in order to call.

A class can be instantiated multiple objects, each object can have different properties. Refers to the use of the human person, everyone refers to specific objects.

c, encapsulated (encapsulation)

In the class assignment of data internal to external calls transparent to the user, which makes the class into a container or capsule, which contains the data and methods of a class.

d, inheritance (Inheritance)

A class can derive subclasses, attributes defined in the parent class, method automatically inherited by subclasses.

e, polymorphism (Polymorphism)

Polymorphism: important characteristic is object oriented, said simple point: "an interface, a variety of implementation," refers to a group derived class different subclasses,

And each subclass inherits the same way at the same time the name of the parent class to do a different realization, this is the show of the same thing a variety of forms.

The program is actually a concrete world abstracting process, polymorphism is a reflection of abstraction.

The number of specific things in common abstracted, and through this abstract things, dialogue with different specific things.

Polymorphism allows the object as an object subclass using the parent class, a reference to its parent type of pointing object subtype, the method calls the sub-types.

The entire code is compiled and before the called method has already decided, and the reference points to an object can be dynamic binding at runtime.

2, object-oriented programming

(1) No matter what form of programming, to be clear about the principles: to write duplicate code is very bad ground-level behavior; before you write code that requires constant updates.

Therefore, the development of procedures to follow and easy to read, easy to change the principles, namely: a readable, easy to expand.

(2) Sample code:

#!/usr/bin/env python

# -*- coding:utf-8 -*-

# Author: ZhengzhengLiu

# Object-oriented simulation game --CS

classRole(object):

def__init__(self,name,role,weapon,life_value=100,money=15000):

        self.name = name

        self.role = role

        self.weapon = weapon

        self.life_value = life_value

        self.money = money

defshot(self):

print("shotting...")

defgot_shot(self):

print("ah...%s got shot..."%self.name)

defbuy_gun(self,gun_name):

print("%s just bought %s"%(self.name,gun_name))

r1 = Role ( "Jack", "police", "AK-47") # instantiated (initialize a class object is created)

r1.buy_gun("B51")

r2 = Role("Amy","terrorist","B22")

r2.got_shot()

#operation result:

Jack just bought B51

ah...Amy got shot...

Note:

The basic definition of a, class

The first sentence: define a class, class is a class definition syntax, Role class name, (object) is writing the new class must be written;

The second sentence: __ init __ () is called initialization method, also known as the constructor (although it is in the form of a function, but in the class is not called function, and called the method), this method will be automatically executed when it is called in the class, some initializing operation,

So __init __ (self, name, role, weapon, life_value = 100, money = 15000) to it is to set these attributes when creating a character.

b, examples of: a put into a particular class of object is called instantiation process.

Here, the example of generating a character, the parameters are automatically passed to the following classes Role the __init __ (...) method.

Initialize a role, you need to call this class time; when you create a role above, did not give __init __ (...) by value, because the class to call its own __init __ (...) to help you is yourself the self parameter assignment.

R1 = performed when Role ( 'liu', 'police', 'AK47'), python interpreter actually did two things:

1, r1 points to open up a space for the variable name in memory.

2. Role call this class and executes the __init __ (...) method, which is equivalent Role .__ init __ (r1, 'Jack', 'police', 'AK47'), why do it?

In order to 'Jack', 'police', 'AK47' It just opened with three values ​​of r1 associate, because the associate, you can directly r1.name, r1.weapon so to call.

So, for the realization of this association, when you call the __init__ method, it must also pass in the variable r1, otherwise, __init__ does not know whom to put those three parameters associated with.

So this __init __ (...) method where, self.name = name, self.role = role and so the meaning is to bring these values ​​to save memory space r1's.

Junction: self is itself an example, an instance of this example, the Python is automatically transferred into the self argument itself.

r1.buy_gun ( "B51") === "Python automatically converted to: Role.buy_gun (r1," B51 ")

Still did not give the value of self pass, but Python or will help you to automatically self r1 assigned to this parameter, and why? Because, you may want to visit some other property r1 in buy_gun (..) method, 

For example, here on a visit r1 name, how to access it? You need to tell this method, so he passed this self r1 parameters, and then call self.name in buy_gun years is equivalent to calling r1.name,

If you want to know how many hit points r1, written directly self.life_value it.

to sum up:

a, above this r1 = Role ( 'Alex', 'police', 'AK47') operation, called the class "instantiation", it is to a virtual abstract class, by this action, into a specific the object, and the object instance is called.

B, the just defined object-oriented class reflects a fundamental characteristic of the first, the package, in fact, the contents of the package using the constructor method to a specific object, and then packaged contents obtained indirectly or directly self through the object.

3, instance variables and class variables

(1) class variable: class exists in memory, can be used without instantiating; instantiated, by way of example may also be called class variables. Action: common attributes save money.

(2)实例变量:描述某个具体对象一些特定的属性,只能在实例本身中使用。

(3)区别:若一个类中,既有类变量name,又有实例变量name,则先找实例变量,实例变量没有的情况下,再找类变量。

#!/usr/bin/env python

# -*- coding:utf-8 -*-

# Author:ZhengzhengLiu

#面向对象--CS游戏模拟

classRole(object):

n =123#类变量

def__init__(self,name,role,weapon,life_value=100,money=15000):

#构造函数

#作用:在实例化时做一些类的初始化工作

self.name = name#实例变量(静态属性),作用域就是实例本身

        self.role = role

        self.weapon = weapon

        self.life_value = life_value

        self.money = money

defshot(self):#类的方法(功能)--动态属性

print("shotting...")

defgot_shot(self):

print("ah...%s got shot..."%self.name)

defbuy_gun(self,gun_name):

print("%s just bought %s"%(self.name,gun_name))

#r1是类Role的一个实例化对象

# 实例化就是以类Role为模板,在内存开辟一块空间,存上数据,赋值成一个变量名

#实例化(初始化一个类,创建了一个对象)

r1 = Role("Jack","police","AK-47")#此时self相当于r1,Role(r1,"Jack","police","AK-47")

r1.buy_gun("B51")#r1也被称作Role的一个实例

r1.name ="liu"#修改r1的实例变量

r1.n ="改变类变量"#在r1中修改类变量n的值,相当于创建一个n,不会影响r2

r1.bullet_prove =True#添加新的属性,只能在r1中使用

print(r1.n)

r2 = Role("Amy","terrorist","B22")#此时self相当于r2,Role(r2,"Amy","terrorist","B22")

r2.got_shot()

print(r2.n)

Role.n ="abc"#通过类名修改类变量的值

print("r1:",r1.n)

print("r2:",r2.n)

#运行结果:

liu just bought B51

改变类变量

ah...Amy got shot...

123

r1: 改变类变量

r2: abc

4、析构函数        def __del__(self):

作用:在实例销毁/释放时自动执行,通常用于做一些收尾工作,如:关闭一些数据库链接,关闭打开临时的文件。

析构函数的调用顺序与构造方法的调用顺序相反。

#!/usr/bin/env python

# -*- coding:utf-8 -*-

# Author:ZhengzhengLiu

#面向对象--CS游戏模拟

classRole(object):

n =123#类变量

def__init__(self,name,role,weapon,life_value=100,money=15000):

#构造函数

#作用:在实例化时做一些类的初始化工作

self.name = name#实例变量(静态属性),作用域就是实例本身

        self.role = role

        self.weapon = weapon

        self.life_value = life_value

        self.money = money

def__del__(self):#析构函数

print("%s game over..."%self.name)

defshot(self):#类的方法(功能)--动态属性

print("shotting...")

defgot_shot(self):

print("ah...%s got shot..."%self.name)

defbuy_gun(self,gun_name):

print("%s just bought %s"%(self.name,gun_name))

r1 = Role("Jack","police","AK-47")

r1.buy_gun("AK47")

r1.got_shot()

r2 = Role("Amy","terrorist","B22")

r2.got_shot()

#运行结果:

Jack just bought AK47

ah...Jack got shot...

ah...Amy got shot...

Amy game over...

Jack game over...

5、私有方法、私有属性(变量) 在变量或者方法前面添加两个下划线 "__",即可变成私有方法、私有属性

私有属性只能在类的内部,通过self使用,在类的外部无法直接访问和修改其内容。

#!/usr/bin/env python

# -*- coding:utf-8 -*-

# Author:ZhengzhengLiu

#面向对象--CS游戏模拟

classRole(object):

n =123#类变量

def__init__(self,name,role,weapon,life_value=100,money=15000):

#构造函数

#作用:在实例化时做一些类的初始化工作

self.name = name#实例变量(静态属性),作用域就是实例本身

        self.role = role

        self.weapon = weapon

self.__life_value = life_value#私有属性/私有变量

        self.money = money

def__del__(self):#析构函数

print("%s game over..."%self.name)

defshow_status(self):#私有属性只能在类的内部使用

print("name:%s weapon:%s life_val:%s"%(self.name,self.weapon,self.__life_value))

defshot(self):#类的方法(功能)--动态属性

print("shotting...")

defgot_shot(self):

self.__life_value -=50

print("ah...%s got shot..."%self.name)

defbuy_gun(self,gun_name):

print("%s just bought %s"%(self.name,gun_name))

r1 = Role("Jack","police","AK-47")

r1.buy_gun("AK47")

r1.got_shot()

r1.show_status()

#运行结果:

Jack just bought AK47

ah...Jack got shot...

name:Jack weapon:AK-47life_val:50

Jack game over...

Guess you like

Origin www.cnblogs.com/waterstar/p/11320891.html