面向对象编程基础(进阶4)
万物皆对象,因学过Java面向对象编程思想,Python也一样,所以简单写下这节
什么是面向对象编程
面向对象编程的基本思想
1 # -*- coding:utf-8 -*- 2 class Person(object): 3 pass 4 5 xiaoming = Person() 6 xiaohong = Person() 7 print xiaoming 8 print xiaohong 9 print xiaoming == xiaohong
1 class Person(object): 2 pass 3 p1 = Person() 4 p1.name = 'Bart' 5 6 p2 = Person() 7 p2.name = 'Adam' 8 9 p3 = Person() 10 p3.name = 'Lisa' 11 12 L1 = [p1, p2, p3] 13 L2 = sorted(L1, lambda p1, p2: cmp(p1.name, p2.name)) 14 15 print L2[0].name 16 print L2[1].name 17 print L2[2].name
在定义 Person 类时,可以为Person类添加一个特殊的__init__()方法,当创建实例时,init()方法被自动调用,我们就能在此为每个实例都统一加上以下属性
1 class Person(object): 2 def __init__(self, name, gender, birth, **kw): 3 self.name = name 4 self.gender = gender 5 self.birth = birth 6 for k, v in kw.iteritems(): 7 setattr(self, k, v) 8 xiaoming = Person('Xiao Ming', 'Male', '1990-1-1', job='Student') 9 print xiaoming.name 10 print xiaoming.job
Python对属性权限的控制是通过属性名来实现的,如果一个属性由双下划线开头(__),该属性就无法被外部访问。
1 class Person(object): 2 def __init__(self, name, score): 3 self.name = name 4 self.__score = score 5 6 p = Person('Bob', 59) 7 8 print p.name 9 print p.__score
每个实例各自拥有,互相独立,而类属性有且只有一份。
1 class Person(object): 2 count = 0 3 def __init__(self, name): 4 Person.count = Person.count + 1 5 self.name = name 6 p1 = Person('Bob') 7 print Person.count # 1 8 9 p2 = Person('Alice') 10 print Person.count # 2 11 12 p3 = Person('Tim') 13 print Person.count # 3
1 class Person(object): 2 __count = 0 3 def __init__(self, name): 4 Person.__count = Person.__count + 1 5 self.name = name 6 print Person.__count 7 8 p1 = Person('Bob') 9 p2 = Person('Alice') 10 11 print Person.__count
1 class Person(object): 2 3 def __init__(self, name, score): 4 self.__name = name 5 self.__score = score 6 7 def get_grade(self): 8 if self.__score >= 80: 9 return 'A' 10 if self.__score >= 60: 11 return 'B' 12 return 'C' 13 14 p1 = Person('Bob', 90) 15 p2 = Person('Alice', 65) 16 p3 = Person('Tim', 48) 17 18 print p1.get_grade() 19 print p2.get_grade() 20 print p3.get_grade()
1 class Person(object): 2 3 def __init__(self, name, score): 4 self.name = name 5 self.score = score 6 self.get_grade = lambda: 'A' 7 8 p1 = Person('Bob', 90) 9 print p1.get_grade 10 print p1.get_grade()
和属性类似,方法也分实例方法和类方法。
1 class Person(object): 2 __count = 0 3 @classmethod 4 def how_many(cls): 5 return cls.__count 6 def __init__(self, name): 7 self.name = name 8 Person.__count = Person.__count + 1 9 10 print Person.how_many() 11 p1 = Person('Bob') 12 print Person.how_many() 13 14