+1s. 面向对象相关

面向对象

Object Oriented Programing(OOP)面向对象编程

1
2
3
4
5
6
7
class Student(object):
def __init__(self, name, score):
self.name = name
self.score = score

def print_score(self):
print('%s: %s' % (self.name, self.score))

类比于java,__init__函数相当于构造函数,self代表自身,必须传的参数。当定义了__init__方法之后,创建其实例时需要将对应的参数也传入。

  1. 成员变量私有化

    1
    2
    3
    def __init__(self,name,score):
    self.__name = name
    self.__score = score
  2. 数据封装

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    class Student(object):

    def __init__(self, name, score):
    self.name = name
    self.score = score

    def print_score(self):
    print('%s: %s' % (self.name, self.score))


    >>> bart.print_score()
    Bart Simpson: 59
  3. 属性私有化
    成员变量前添加_即是将变量私有化,使其无法被外部直接访问,可以添加get,set方法进行间接访问。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    def __init__(self, name, score):
    self.__name = name
    self.__score = score

    def get_name(self):
    return self.__name

    def get_score(self):
    return self.__score

    def set_score(self, score):
    self.__score = score

    def set_score(self, score):
    if 0 <= score <= 100:
    self.__score = score
    else:
    raise ValueError('bad score')
  4. 继承多态

    父类:

    1
    2
    3
    class Animal(object):
    def run(self):
    print('Animal is running...')

    子类:

    1
    2
    3
    4
    5
    6
    7
    class Dog(Animal):

    def run(self):
    print('Dog is running...')

    def eat(self):
    print('Eating meat...')

    关系:

    1
    2
    >>> isinstance(c, Animal)
    True
  5. 获取对象信息

    • type():

      1
      2
      >>> type(123)
      <class 'int'>
      1
      2
      >>> type('str')
      <class 'str'>
      1
      2
      >>> type(None)
      <type(None) 'NoneType'>
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      >>> import types
      >>> def fn():
      pass

      >>> type(fn)==types.FunctionType
      True
      >>> type(abs)==types.BuiltinFunctionType
      True
      >>> type(lambda x: x)==types.LambdaType
      True
      >>> type((x for x in range(10)))==types.GeneratorType
      True

      # 判断两个变量类型是否相同
      >>> type(123) == type(456)
      true
    • isinstance():

      1
      2
      3
      4
      5
      6
      >>> isinstance('a', str)
      True
      >>> isinstance(123, int)
      True
      >>> isinstance(b'a', bytes)
      True
    • dir():
      获得对象的所有属性和方法:

      1
      2
      >>> dir('ABC')
      ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
    • 获取各项属性:
      创建实例对象:

      1
      2
      3
      4
      5
      6
      7
      class MyObject(object):
      def __init__(self):
      self.x = 9
      def power(self):
      return self.x * self.x

      obj = MyObject()

      各项方法:

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      >>> hasattr(obj, 'x') # 有属性'x'吗?
      True
      >>> obj.x
      9
      >>> hasattr(obj, 'y') # 有属性'y'吗?
      False
      >>> setattr(obj, 'y', 19) # 设置一个属性'y'
      >>> hasattr(obj, 'y') # 有属性'y'吗?
      True
      >>> getattr(obj, 'y') # 获取属性'y'
      19
      >>> obj.y # 获取属性'y'
      19

      >>> hasattr(obj, 'power') # 有属性'power'吗?
      True
      >>> getattr(obj, 'power') # 获取属性'power'
      <bound method MyObject.power of <__main__.MyObject object at 0x10077a6a0>>
      >>> fn = getattr(obj, 'power') # 获取属性'power'并赋值到变量fn
      >>> fn # fn指向obj.power
      <bound method MyObject.power of <__main__.MyObject object at 0x10077a6a0>>
      >>> fn() # 调用fn()与调用obj.power()是一样的
      81

面向对象高级编程

  1. 为对象和类添加方法

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    class Student():
    pass

    s = Student()
    # 1.添加属性
    s.name = 'Michael'

    # 2.为对象添加方法
    def set_age(self, age):
    self.age = age

    form types import MethodType
    s.set_age = MethodType(set_age, s)

    # 3.为类添加方法
    def set_gender(self, gender):
    self.gender = gender

    Student.set_gender = set_gender
  2. __slots__属性:
    类里限制一些能被修改的属性:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    # 限定只有name和age能被修改,
    class Student(object):
    __slots__ = ('name', 'age');

    >>> s = Student() # 创建新的实例
    >>> s.name = 'Michael' # 绑定属性'name'
    >>> s.age = 25 # 绑定属性'age'
    >>> s.score = 99 # 绑定属性'score'
    #报错

    ps:只对当前类有效,子类无效。

  3. @property方法
    get方法使用@property进行包装,便自动生成一个对应的set方法的注解

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    class Student(object):

    @property
    def birth(self):
    return self._birth

    @birth.setter
    def birth(self, value):
    self._birth = value

    @property
    def age(self):
    return 2015 - self._birth
  4. 多继承

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    class Animal(object):
    pass

    # 大类:
    class Mammal(Animal):
    pass

    class Bird(Animal):
    pass

    # 各种动物:
    class Dog(Mammal):
    pass

    class Bat(Mammal):
    pass

    class Parrot(Bird):
    pass

    class Ostrich(Bird):
    pass

    # 动物的性质:
    class Runnable(object):
    def run(self):
    print('Running...')

    class Flyable(object):
    def fly(self):
    print('Flying...')

    #多继承的蝙蝠
    class Bat(Mammal, Flyable):
    pass

    对于bat来说 Animal 和Mammal都是主线,而Flyable是支线,这样混入支线的设计叫做MixIn,命名时可能也会使用FlyableMixIn。