Python之面向对象

创建类:

  class class_name(upper):

    

类的初始化:

  

 1 class Test:
 2 
 3     def __init__(self, foo):
 4         self.__foo = foo
 5 
 6     def __bar(self):
 7         print(self.__foo)
 8         print('__bar')
 9 
10 ...
11 __var
12 __function_name()
13 以双下划线开头的表示私有属性或方法
14 可以用getter或setter方法获得
15 
16 定义getter方法
17 @property
18 def name(参数):
19 return or print()        
20 
21 @name.setter
22 def name(参数):
23 self._name=name
24 
25 必须现有getter方法才能设置setter方法
26 ...
27 
28 
29 还可以以一种方法访问:
30 
31 class Test:
32 
33     def __init__(self, foo):
34         self.__foo = foo
35 
36     def __bar(self):
37         print(self.__foo)
38         print('__bar')
39 
40 
41 def main():
42     test = Test('hello')   
43     test._Test__bar()   # _Test访问
44     print(test._Test__foo)
45 
46 
47 if __name__ == "__main__":
48     main()

 面向对象进阶

__slots__限制当前类绑定的属性

1  # 限定Person对象只能绑定_name, _age和_gender属性
2     __slots__ = ('_name', '_age', '_gender')

静态方法

1 # Python有有静态方法和类方法,静态方法通过类名调用
2 
3 # 静态方法通过 @staticmethod 修饰
4 @staticmethod
5     def is_valid(a, b, c):
6         return a + b > c and b + c > a and a + c > b

类方法

和静态方法比较类似,Python还可以在类中定义类方法,类方法的第一个参数约定名为cls,它代表的是当前类相关的信息的对象(类本身也是一个对象,有的地方也称之为类的元数据对象)

1 @classmethod
2     def now(cls):
3         ctime = localtime(time())
4         return cls(ctime.tm_hour, ctime.tm_min, ctime.tm_sec) # 相当与执行当前类的构造方法,然后再返回
5 
6 
7 ...
8 参数cls为默认参数,表示当前类的对象

类和类之间的关系

简单的说,类和类之间的关系有三种:is-a、has-a和use-a关系。

  

  • is-a关系也叫继承或泛化,比如学生和人的关系、手机和电子产品的关系都属于继承关系(用的较多)

  

  • has-a关系通常称之为关联,比如部门和员工的关系,汽车和引擎的关系都属于关联关系;关联关系如果是整体和部分的关联,那么我们称之为聚合关系;如果整体进一步负责了部分的生命周期(整体和部分是不可分割的,同时同在也同时消亡),那么这种就是最强的关联关系,我们称之为合成关系。
  • use-a关系通常称之为依赖,比如司机有一个驾驶的行为(方法),其中(的参数)使用到了汽车,那么司机和汽车的关系就是依赖关系。

继承和多态 

子类在继承了父类的方法后,可以对父类已有的方法给出新的实现版本,这个动作称之为方法重写(override)。通过方法重写我们可以让父类的同一个行为在子类中拥有不同的实现版本,当我们调用这个经过子类重写的方法时,不同的子类对象会表现出不同的行为,这个就是多态(poly-morphism)。

 1 class Student(Person):      # 继承一般在类名之后的括号里写父类的名字
 2 
 3 
 4 # Person为父类
 5 
 6 # 抽象方法用@abstractmethod标明
 7 
 8 @abstractmethod
 9     def make_voice(self):
10         """发出声音"""
11         pass
原文地址:https://www.cnblogs.com/cherrydream/p/11353220.html