python难点:面向对象编程(OOP)

学习廖雪峰官方网站python教程总结
python面向对象编程OOP(Object Oriented Programming)总结,供日后参考
1.类和实例

#类的定义
class Student(object):
    #限制实例只能添加指定的属性
    __slots__ = ('sex','age')
    #类属性
    school = 'QingHua'
    #初始化值,创建实例必须绑定的属性
    def __init__(self,name,score):
        #private变量
        self.__name = name
        self.__score = score
    #设置getter,setter保证类内部数据安全
    def get_name(self):
        return self.__name
    def get_score(self):
        return self.__score
    def set_name(self,name):
        self.__name = name
    def set_score(self,score):
        self.__score = score
    def hello(self,name='world'):
        print('Hello, %s.' % name)
#type()创建类,type()实质上是元类(metaclass),类的定义本质上就是利用type()创建类
def fn(self, name='world'): # 先定义函数
    print('Hello, %s.' % name)
Student = type('Student',(object,),dict(hello=fn))

#创建实例
jim = Student('Jim',120)
print(jim.school) #QingHua
print(jim.name) #Jim
print(Student.school) #QingHua
jim.age = 20
jim.height = 170 #报错,不能添加__slots__未指定的属性

2.@property
上例中,为了保护内部数据的安全,我们使用setter,getter方式封装数据,能够防止用户随心所欲地修改数据,但是不够简洁。使用@property装饰器可以帮助我们改造成我们想要的样子

class Student(object):
    def __init__(self,birth):
        #private变量
        self.__birth = birth
    @property 
    def birth(self):
        return self.__birth
    @birth.setter
    def birth(self,value):
        self.__birth = value
    @property
    def age(self):
        return 2018-self.__birth
#birth为可读写属性,age是只读属性
s = Student(1995)
s.birth #实际转化为s.get_birth  结果:1995
s.birth = 1996 #实际转化为s.set_birth 
s.age #22
s.age = 20 #报错,当前age为只读属性

3.继承和多态

class Animal(object):
    def run(self):
        print('Animal is running')
class Dog(Animal):
    def run(self):
        print('Dog is runing')
class Cat(Animal):
    pass
dog = Dog()
cat = Cat()
dog.run() #Dog is running Dog类重写了Animal的run方法
cat.run() #Animal is running Cat类继承了Animal的run方法

#多态
def run_log(obj):
    obj.run()
run_log(Animal()) #Animal is running
run_log(Dog()) #Dog is running
#传说中的file-like object
class other(object):
    def run():
        print('other is running')
#传入任何实现run方法的对象都可以,这就是动态语言多分魅力
run_log(other) #other is running

4.自定义类

#__str__让class作用于print()
class Student(object):
    def __init__(self,name):
        self.name = name
    def __str__(self):
        return 'Student name:%s' % self.name
    #__repr__用于调试服务,__str__用于用户打印
    __repr__ = __str__
print(Student('Tom')) # Student name:Tom

#__iter__
#将class处理成tuple或list可迭代
class Fib(object):
    def __init__(self):
        self.a,slef.b = 0,1
    def __iter__(self):
        return self
    def __next__(self):
        self.a,self.b = self.b,self.a+self.b
        if self.a>100
            raise StopIteration()
        return self.a
for n in Fib():
    print(n)
#1 1 2 3 5 8 13 21 34 55 89   

#__getitem__()  __getattr__()  __call__()方法,以后用的时候具体了解

5.枚举类

from enum import Enum
Month = Enum('Month',('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'))
for name,member in Month.__members__.items():
    print(name,'=>',member,',',member.value)
#value属性自动赋给成员int变量,默认从1开始
#Enum派生自定义类

from enum import Enum,unique
@unique
class Weekday(Enum):
    Sun = 0
    Mon = 1
    Tue = 2
    Wed = 3
    Thu = 4
    Fri = 5
    Sat = 6
#@unique装饰器帮助我们检查保证没有重复值
    

    原文作者:王鹏宇
    原文地址: https://segmentfault.com/a/1190000013132612
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞