您的位置:首页 > 编程语言 > Python开发

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

2015-10-16 14:09 369 查看
一、首先来理解几个面向对象的关键特性:

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

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

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

二、创建自己的类

>>> class Person:
...     def setname(self,name):
...             self.name = name
...     def getname(self):
...             return self.name
...
>>> p = Person()
>>> p.setname('darren')
>>> p.getname()
'darren'


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

>>> class Sercrt:
...     def greet(self):
...             print("hello,abc")
...     def __greet1(self):
...             print("i don't tell you ")
...
>>> s = Sercrt()
>>> s.greet()
hello,abc
>>> s.__greet1()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: Sercrt instance has no attribute '__greet1'


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

>>> class Bird:
...     def fly(self):
...             print("I want to fly more and more higher")
...
>>> class Swallow(Bird):
...     def fly(self):
...             print("Swallow can fly")
...
>>>
>>> s = Swallow()
>>> s.fly()
Swallow can fly


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

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

2、属性:porperty(get,set)

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

>>> class Myclass:
...     @staticmethod
...     def smeth():
...             print("i am static method")
...     @classmethod
...     def cmeth(cls):
...             print("i am class method")
...
>>>
>>> Myclass.smeth()
i am static method
>>> Myclass.cmeth()
i am class method


      
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: