对象 = 属性 + 方法
下面是一个关于类的简单例子
class Turtle: #Python中的类名约定以大写字母开头
"""关于类的一个简单例子"""
#属性
color = 'green'
weight = 10
legs = 4
shell = True
mouth = '大嘴'
#方法
def climb(self):
print('我在努力向前爬....')
def run(self):
print('我正在飞快的向前跑....')
def bite(self):
print('咬死你咬死你...')
def eat(self):
print('有吃的,真满足....')
def sleep(self):
print('困了,睡了...')
>>> ================================ RESTART ================================
>>>
>>> Turtle()
<__main__.Turtle object at 0x022B2E50>
>>> tt = Turtle()
>>> tt
<__main__.Turtle object at 0x022B2DF0>
>>> tt.climb()
我在努力向前爬....
>>> tt.run()
我正在飞快的向前跑....
>>> tt.bite()
咬死你咬死你...
>>> tt.eat()
有吃的,真满足....
>>> tt.sleep()
困了,睡了...
Python是面向对象的程序语言
第一个特征:封装
第二个特征:继承
继承是子类自动共享父类之间数据和方法的机制。
例如:定义一个类继承列表,Mylist继承了list的方法和属性。
>>> class MyList(list): #继承list
pass
>>> list1 = MyList()
>>> list1.append(4)
>>> list1.append(9)
>>> list1.append(6)
>>> list1
[4, 9, 6]
>>> list1.sort()
>>> list1
[4, 6, 9]
>>>
第三个特征:多态
不同对象对同一方法响应不同的行动。
>>> class A:
def fun(self):
print('I am A....')
>>> class B:
def fun(self):
print('I am B ....')
>>> a = A()
>>> b = B()
>>> a.fun()
I am A....
>>> b.fun()
I am B ....
>>>
OOA:面向对象分析
OOD:面向对象设计
OOP:面向对象编程
self是什么?
Python的self相当于C++的this指针。在Python的累的定义的时候把self写进第一个参数。
>>> class Ball:
def setName(self,name):
self.name = name
def kick(self):
print('我叫%s,你好....' % self.name)
>>> a = Ball()
>>> a.setName('ballA')
>>> b = Ball()
>>> b.setName('ballB')
>>> c = Ball()
>>> c.setName('tomato')
>>> a.kick()
我叫ballA,你好....
>>> c.kick()
我叫tomato,你好....
>>> b.kick()
我叫ballB,你好....
>>>
Python的魔法方法
__init__(self)称之为构造方法。
只要实例化一个对象的时候,那么这个方法就会在对象被创建的时候自动调用。
所有实例化对象的时候是可以传入参数的,这些参数会自动的传入到init方法中。
可以通过重写这个方法,来自定义对象的初始化操作。
例子:
>>> class Ball:
def __init__(self,name):
self.name = name
def kick(self):
print('我叫%s,你好....' % self.name)
>>> a = Ball('BallA')
>>> b = Ball('tomato')
>>> a.kick()
我叫BallA,你好....
>>> b.kick()
我叫tomato,你好....
>>>
共有和私有
为了实现类似私有变量的特征,Python内部采用name mangling(名字改编,名字重整)技术。
在Python中定义私有变量只需要在变量名或函数名前加上"_"两个下划线,那么这个函数或变量就会为私有的了。
首先看一下共有变量的访问:
>>> class Person:
name = 'banner'
>>> p = Person()
>>> p.name
'banner'
>>>
>>> class Person:
__name = 'banner'
>>> p = Person()
>>> p.name
Traceback (most recent call last):
File "<pyshell#39>", line 1, in <module>
p.name
AttributeError: 'Person' object has no attribute 'name'
>>> p.__name
Traceback (most recent call last):
File "<pyshell#40>", line 1, in <module>
p.__name
AttributeError: 'Person' object has no attribute '__name'
>>>
>>> class Person:
__name = 'banner'
def getName(self):
return self.__name
>>> p = Person()
>>> p.getName()
'banner'
>>>
>>> p = Person()
>>> p._Person__name
'banner'
>>>
就目前来说Python私有机制就是伪私有,Python的类是没有权限控制的,变量是可以被外部调用的。