面向对象的语言除了封装。继承还有多态。 多态必须满足两个条件
class A1:
def defs(self):
print("1")
class A2(A1):
def defs(self):
print('2')
class A3(A1):
def defs(self):
print("3")
a = A1()
a.defs()
a = A2()
a.defs()
a = A3()
a.defs()
1
2
3
以上实例反应在类之间的继承和方法的重写。在调用同一个方法时。由于a代表不同的实例对象。 因此a.defs()在调用时不是调用同一个类中的方法。 而是调用各自类中的方法。这就是多态,
class A0:
def defs(self, who):
who.defs()
class A1:
def defs(self):
print("1")
class A2(A1):
def defs(self):
print('2')
class A3(A1):
def defs(self):
print("3")
a = A0()
a.defs(A1())
a.defs(A2())
a.defs(A3())
1
2
3
新建一个类在这个类中添加了一个同名的方法。而这个方法有额外带了一个除self的参数。 通过这个参数调用方法。 这样以来只需要传入传入各自的实例对象就可以调用各自的方法了。
对于一些特殊的类来说其实例化对象的个数往往也是一定的。例如月份类最多可以实例化12个对象。对于这种特殊的类python3.4就增加了Enum枚举类。换句话说对于实例对象个数一定的类可以用枚举类来实现,
from enum import Enum
class School(Enum):
name = 1
age = 2
city = 3
枚举类的成员有两部分组成
枚举类是不能直接实例化成对象的。枚举一般有以下几种操作方式
from enum import Enum
class School1(Enum):
name = 1
age = 2
city = 3
print(School1.name)
print(School1['name'])
print(School1(1))
print(School1(3))
School1.name
School1.name
School1.name
School1.city
from enum import Enum
class School1(Enum):
name = 1
age = 2
city = 3
print(School1.name.value)
print(School1.age.name)
1
age
from enum import Enum
class School1(Enum):
name = 1
age = 2
city = 3
for key in School1:
print(key)
School1.name
School1.age
School1.city
from enum import Enum
class School1(Enum):
name = 1
age = 2
city = 1
print(School1.name == School1.age)
print(School1["name"] is School1.city)
False
True
from enum import Enum
class School1(Enum):
name = 1
age = 2
city = 3
School1.name = 4
Traceback (most recent call last):
File "/Users/apple/Documents/重要文件/python3/python21.py", line 7, in
School1.name = 4
File "/usr/local/Cellar/python/3.7.5/Frameworks/Python.framework/Versions/3.7/lib/python3.7/enum.py", line 386, in __setattr__
raise AttributeError('Cannot reassign members.')
AttributeError: Cannot reassign members.
from enum import Enum
class School1(Enum):
name = 1
age = 2
city = 3
for key,value in School1.__members__.items():
print(key,"-------", value)
name ------- School1.name
age ------- School1.age
city ------- School1.city
from enum import Enum,unique
class School1(Enum):
name = 1
age = 2
city = 1
print(School1.city)
School1.name
但是结果却有点诧异。 出现这样的原因在于它将city当成了name的别名。 可以添加@unique 装饰器装饰器。当出现相同的成员时程序会抛出异常。
from enum import Enum,unique
@unique
class School1(Enum):
name = 1
age = 2
city = 1
print(School1.city)
Traceback (most recent call last):
File "/Users/apple/Documents/重要文件/python3/python21.py", line 4, in
class School1(Enum):
File "/usr/local/Cellar/python/3.7.5/Frameworks/Python.framework/Versions/3.7/lib/python3.7/enum.py", line 869, in unique
(enumeration, alias_details))
ValueError: duplicate values found in : city -> name
from enum import Enum
School = Enum("School", ("name", "age", 'city'))
print(School.name)
print(School['name'])
print(School(1))
print(School.name.name)
print(School.name.value)
for key in School:
print(key)
School.name
School.name
School.name
name
1
School.name
School.age
School.city