python list指定list数据成员类型
背景
python list指定list数据成员类型,方便提示设计架构思想,并方便IDE调转。
示例
class Student:
def __init__(self, name: str, score: int):
self.name: str = name
self.score: int = score
def __str__(self):
return f"Student({repr(self.name)}, {repr(self.score)})"
class ClassRoom:
def __init__(self):
# 指定list数据成员类型为Student类,List是list的范型,用作类型标注/提示(type annotation)
self.students: List[Student] = []
def __str__(self) -> str: # 指定返回类型实例
return f"len(students): {len(self.students)}"
if __name__ == "__main__":
class_room = ClassRoom()
class_room.students.append(Student("xiaoming", 99))
print(class_room.students[0]) # 在IDE里将class_room.students[0]识别为Student类
在pycharm里,可以识别class_room.students[0]识别为Student类,并提示成员属性、调转到定义:
参考/扩展
python范型: https://zhuanlan.zhihu.com/p/497801684