Python快速学习05:面向对象


 Python对象是Python语言的核心部分。Python使用类(class)和对象(object),进行面向对象(object-oriented programming,简称OOP)的编程。
 
面向对象的最主要目的是提高程序的重复使用性。
 
 
 
Python的类
 
例子
 
class Bird(object):
    have_feather = True
    way_of_reproduction  = 'egg'
print (id(Bird))
#内建函数id():唯一的身份标识
 
#两个变量(属性),一个是有羽毛(have_feather),一个是生殖方式(way_of_reproduction)
 
 
 
实例化
 
summer = Bird()
print (summer.way_of_reproduction)
#对象.属性(object.attribute)访问属性值
 
 
 
类中方法(method)
 
   类的一些“行为”属性为方法(method)。Python中通过在类的内部定义函数,来说明方法。
 
例子
 
复制代码
class Bird(object):
    have_feather = True
    way_of_reproduction = 'egg'
    def move(self, dx, dy):
        position = [0,0]
        position[0] = position[0] + dx
        position[1] = position[1] + dy
        return position
 
summer = Bird()
print ('after move:',summer.move(5,8))
复制代码
#参数中有一个self,它是为了方便我们引用对象自身。方法的第一个参数必须是self。
 
 
 
子类
 
  类别本身还可以进一步细分成子类
 
在OOP中,我们通过继承(inheritance)来表达上述概念
 
复制代码
class Chicken(Bird):
    way_of_move = 'walk'
    possible_in_KFC = True
 
class Oriole(Bird):
    way_of_move = 'fly'
    possible_in_KFC = False
 
summer = Chicken()
print (summer.have_feather)
print (summer.move(5,8))
复制代码
#在类定义时,括号里为Bird。这说明,Chicken是属于鸟类(Bird)的一个子类,即Chicken继承自Bird。自然而然,Bird就是Chicken的父类。Chicken将享有Bird的所有属性。
 
#尽管我只声明了summer是鸡类,它通过继承享有了父类的属性(无论是变量属性have_feather还是方法属性move)
 
 
 
self
 
例子
 
复制代码
class Human(object):
    laugh = 'hahahaha'
    def show_laugh(self):
        print (self.laugh)
    def laugh_100th(self):
        for i in range(100):
            self.show_laugh()
 
li_lei = Human()
li_lei.laugh_100th()
复制代码
#这里有一个类属性laugh。在方法show_laugh()中,通过self.laugh,调用了该属性的值。
 
#还可以用相同的方式调用其它方法。方法show_laugh(),在方法laugh_100th中()被调用。
 
 
 
__init__()
 
  __init__()是一个特殊方法(special method),用于初始化。Python有一些特殊方法。Python会特殊的对待。
 
例子
 
class happyBird(Bird):
    def __init__(self,more_words):
        print ('We are happy birds.',more_words)
 
summer = happyBird('Happy,Happy!!')
 
 
会有下面输出
 
We are happy birds.Happy,Happy!
#创建了summer对象,但__init__()方法被自动调用了。
 
 
 
总结
 
  #所有的Python 对象都拥有三个特性:身份,类型和值。
 
 

评论关闭