第四章 python中的面向对象设计

一、首先来理解几个面向对象的关键特性:

1、封装:对象可以将他们的内部状态隐藏起来。python中所有特性都是公开可用的。

2、继承:一个类可以是一个或多个类的子类。python支持多重继承,使用时需要注意继承顺序。

3、多态:实现将不同类型的类的对象进行同样对待的特性--不需要知道对象属于哪个类就能调用方法。

二、创建自己的类

 1 >>> class Person:           
 2 ...     def setname(self,name):
 3 ...             self.name = name
 4 ...     def getname(self):
 5 ...             return self.name
 6 ... 
 7 >>> p = Person()
 8 >>> p.setname('darren')
 9 >>> p.getname()
10 'darren'

很简单吧,这里有个self参数需要说明的,可以称为对象自身,它总是作为对象方法的第一个参数隐式传入!那么类中的有些方法不想被外部访问怎么办?
可以在方法前加双下划线,如下:

 1 >>> class Sercrt:
 2 ...     def greet(self):
 3 ...             print("hello,abc")
 4 ...     def __greet1(self):
 5 ...             print("i don't tell you ")
 6 ... 
 7 >>> s = Sercrt()
 8 >>> s.greet()
 9 hello,abc
10 >>> s.__greet1()
11 Traceback (most recent call last):
12   File "<stdin>", line 1, in <module>
13 AttributeError: Sercrt instance has no attribute '__greet1'

如何指定超类呢?通过子类后面跟上括号里面写入基类即可实现。

 1 >>> class Bird:       
 2 ...     def fly(self):
 3 ...             print("I want to fly more and more higher")
 4 ... 
 5 >>> class Swallow(Bird):
 6 ...     def fly(self):
 7 ...             print("Swallow can fly")
 8 ... 
 9 >>> 
10 >>> s = Swallow()    
11 >>> s.fly()
12 Swallow can fly

 1、构造方法:创建一个新对象时,调用构造方法,用于类的初始化

python中用__init__()表示构造方法,当子类继承父类时,如果子类重写了构造方法,这时如果要继承父类的构造方法,需要用super(子类,self).__init__()

2、属性:porperty(get,set)

3、静态方法和类成员方法:这两种方法无需创建对象,直接通过类名称进行调用,如下:

 1 >>> class Myclass:
 2 ...     @staticmethod
 3 ...     def smeth():
 4 ...             print("i am static method")
 5 ...     @classmethod
 6 ...     def cmeth(cls):
 7 ...             print("i am class method")
 8 ... 
 9 >>> 
10 >>> Myclass.smeth()
11 i am static method
12 >>> Myclass.cmeth()
13 i am class method

      

原文地址:https://www.cnblogs.com/mysql-dba/p/4885158.html