chapter 9 特殊方法、特性和迭代器(reading notes)

9.1 基本概念

  • 以双下划线开头和结尾的方法,大多是特殊方法的名称;
    不可在函数中创建这种类型的名称;
  • property:特性;
    iterator:迭代器;

9.2 构造函数

  • 构造函数(constructor)init(),用于初始化;
    构造函数将在对象创建时,被自动调用;
  • 析构函数(destructor)

9.2.1 重写构造函数

  • 若在子类中重写构造函数,则超类中的构造函数将不能在子类中被应用(因为被覆盖了);
    solution:
    • 调用未关联的超类构造函数;
    • 使用函数 super(在较新版本的 Python 中,应使用本方法) ;

9.2.2 调用未关联的超类构造函数

>>> class Bird:
...     def __init__(self):
...         self.hungry = True
...     def eat(self):
...         if self.hungry:
...             print('Aaaah ...')
...             self.hungry = False
...         else:
...             print('No, thanks!')

... class SongBird(Bird):
...     def __init__(self):
...         Bird.__init__(self)           # 使用超类的构造函数初始化 SongBird 对象;
...         self.sound = 'Squawk!'
...     def sing(self):
...         print(self.sound)
  • 对实例调用方法时,self 参数将自动关联到实例,称之为关联的方法;
  • 通过类调用方法(e.g. Bird.__init__),则没有实例与之相关联,称之为未关联的方法;

9.2.3 使用函数 super

  • 使用 super().__init__() 语句,替换 9.2.2 中的 Bird.__init__(self);
  • 调用 super(当前类的名称, self) 函数时,使用当前类和当前实例(形参为 self )作为参数,返回超类;
    此时调用的方法为超类的方法,而非当前类的方法;
  • 调用 super() 函数时,可不提供任何参数;

9.3 元素访问

9.3.1 基本的序列和映射协议-None

9.3.2 从 list、dict 和 str 派生

# 从 list 继承得到 CounterList ;
>>> class CounterList(list):
...     def __init__(self, *args):        # 重写 __init__() ;
...         super().__init__(*args)       # super() 函数调用超类的构造函数用于初始化;
...         self.counter = 0              # 引入新的 attribute ;
...     def __getitem__(self, index):
...         self.counter += 1             # 对新的 attribute 操作;
...         return super(CounterList, self).__getitem__(index)
                                          # super().__getitem__(index) 亦可;
                                          # 即不向 super() 函数提供参数(见 9.2.3 );

9.4 其他特殊方法-None

9.5 特性

  • property(特性):通过存取方法定义的 attribute ;

9.5.1 函数 property

  • 函数 property 可避免编写大量存取 attribute 的方法;
  • property(fget, fset, fdel, doc)
    该函数四个参数均为可选参数;
    若不指定任何参数,则创建的特性不可读且不可写;
>>> class Rectangle:
...     def __init__(self):
...         self.width = 0
...         self.height = 0
...     def set_size(self, size):
...         self.width, self.height = size
                                          # 给 size 赋值时应为两个值,value1,value2 ;
...     def get_size(self):
...         return self.width, self.height    
...     size  = property(get_size, set_size)
                                          # 调用 property 函数创建一个特性,并与名称 size 关联; 
>>> r = Rectangle() 
>>> r.size = 150, 100                     # 创建的名称 size 如同 attribute 一样调用;                                    

9.5.2 静态方法和类方法

  • 使用 staticmethod、classmethod 方法后,无需实例化即可调用类中定义的方法;

>>> class MyClass:
...     def smeth():                      # staticmethod 的定义中没有形参;
...         print('This is a static method')
...     smeth = staticmethod(smeth)       # 旧的 staticmethod ;

...     def cmeth(cls):                   # classmethod 方法的定义中的形参习惯上被命名为 cls ;
...         print('This is a class method of', cls)
...     cmeth = classmethod(cmeth)        # 旧的 classmethod ;

# --------------------------------------------------------------------------------------------------

>>> class MyClass:
    @staticmethod                         # 装饰器;
    def smeth():
        print('This is a static method')

    @classmethod                          # 装饰器;
    def cmeth(cls):
        print('This is a class method of', cls)

9.5.3 __getattr__、__setattr__等方法

猜你喜欢

转载自blog.csdn.net/Maximize1/article/details/82112974
今日推荐