Python18

Python学习笔记(2)OOP编程

2017-09-17  本文已影响9人  不掉发码农

中文学习网站: 廖雪峰的官网网站https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000

2. OOP 面向对象编程

类的访问限制

class Student(object):
    __slots__ = ('name', 'age') # 用tuple定义允许绑定的属性名称
>>> s.age = 25 # 绑定属性'age'
>>> s.score = 99 # 绑定属性'score'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Student' object has no attribute 'score'

注意:_slots_定义的属性仅对当前类实例起作用,对继承的子类是不起作用的

给实例绑定方法

>>> def set_age(self, age): # 定义一个函数作为实例方法
...     self.age = age
...
>>> from types import MethodType
>>> s.set_age = MethodType(set_age, s) # 给实例绑定一个方法
>>> s.set_age(25) # 调用实例方法
>>> s.age # 测试结果
25

@property装饰器

class Student(object):
    #get接口
    @property
    def score(self):
        return self._score
    #set接口
    @score.setter
    def score(self, value):
        if not isinstance(value, int):
            raise ValueError('score must be an integer!')
        if value < 0 or value > 100:
            raise ValueError('score must between 0 ~ 100!')
        self._score = value
>>> s = Student()
>>> s.score = 60 # OK,实际转化为s.set_score(60)
>>> s.score # OK,实际转化为s.get_score()
60
>>> s.score = 9999
Traceback (most recent call last):
  ...
ValueError: score must between 0 ~ 100!

实例属性与类属性的区别

实例属性是在类中定义,可以通过类或实例访问,但如果给实例绑定一个同名的属性,实例属性会把类属性覆盖掉
如下例子中,当调用s.name = 'Michael'时,s中其实有两个同名的name属性,一个是类属型("Student"),一个是实例属性("Michael"),实例属性会将类属性覆盖掉,直到它被删掉。

>>> class Student(object):
...     name = 'Student'
...
>>> s = Student() # 创建实例s
>>> print(s.name) # 打印name属性,因为实例并没有name属性,所以会继续查找class的name属性
Student
>>> print(Student.name) # 打印类的name属性
Student
>>> s.name = 'Michael' # 给实例绑定name属性
>>> print(s.name) # 由于实例属性优先级比类属性高,因此,它会屏蔽掉类的name属性
Michael
>>> print(Student.name) # 但是类属性并未消失,用Student.name仍然可以访问
Student
>>> del s.name # 如果删除实例的name属性
>>> print(s.name) # 再次调用s.name,由于实例的name属性没有找到,类的name属性就显示出来了
Student

绑定方法与_slots_

给实例绑定一个方法,注意:

>>> def set_age(self, age): # 定义一个函数作为实例方法
...     self.age = age
...
>>> from types import MethodType
>>> s.set_age = MethodType(set_age, s) # 给实例绑定一个方法

给类绑定方法:直接赋值,但函数第一个参数必须为self

>>> def set_score(self, score):
...     self.score = score
...
>>> Student.set_score = set_score

使用_slots_可以限制添加实例的属性(包括变量 和方法)

类中的特殊函数

s = Student()
print(s) #调用__str__
s  #调用__repr__
class Fib(object):
    def __init__(self):
        self.a, self.b = 0, 1 # 初始化两个计数器a,b

    def __iter__(self):
        return self # 实例本身就是迭代对象,故返回自己

    def __next__(self):
        self.a, self.b = self.b, self.a + self.b # 计算下一个值
        if self.a > 100000: # 退出循环的条件
            raise StopIteration()
        return self.a # 返回下一个值

>>> for n in Fib():
...     print(n)
...
1
1
2
3
5
...
46368
75025
class Fib(object):
    def __getitem__(self, n):
        a, b = 1, 1
        for x in range(n):
            a, b = b, a + b
        return a
>>> f = Fib()
>>> f[0]
1
class Student(object):
    def __init__(self, name):
        self.name = name

    def __call__(self):
        print('My name is %s.' % self.name)
        
>>> s = Student('Michael')
>>> s() # self参数不要传入, 调用s.__call__()
My name is Michael.

>>> callable(Student())
True

通过callable()函数,我们就可以判断一个对象是否是“可调用”对象。

上一篇 下一篇

猜你喜欢

热点阅读