python - 更改继承成员的提示类型
问题描述
假设我有一个类的类型提示成员,当我继承时,我想将该成员的提示类型更改为继承类型。那可能吗?
class Animal:
pass
class Dog(Animal):
def look_for_bone(self):
print("Found a bone.")
class Home:
def __init__(self, occupant: Animal):
self.occupant: Animal = occupant
class Kenel(Home):
def __init__(self, occupant: Dog):
super(Kenel, self).__init__(occupant)
# Here I KNOW that the occupant isn't just an Animal, it's a Dog.
self.occupant: Dog
# I've also tried `assert isinstance(self.occupant, Dog)`
# and `assert isinstance(occupant, Dog)`.
fenton = Dog()
k = Kenel(fenton)
print(type(k.occupant))
# I want my IDE to be able to tab-complete look_for_bone on k.occupant
k.occupant.look_for_bone()
k.occupant.look_for_bone()
上面的代码在“类 Animal 的未解析属性引用“look_for_bone”上生成一个 IDE (PyCharm) 警告。但它运行良好:
<class '__main__.Dog'>
Found a bone.
解决方案
推荐阅读
- apache-spark - 解析日期格式
- javascript - 在 display:flex 中,如何指定元素的宽度?
- python - 对象检测 Tensorflow 2.6-如何保存所有检查点并为所有检查点运行 eval
- r - 在ggplot直方图中排序计数
- iot - 如何查看已发布到 Azure IoT Hub 的原始数据(二进制传感器数据)?
- java - AWS EC2 上的 Spring Boot 应用程序仅在 localhost 上运行
- c# - 如何在 ASP.NET Core 6 中使用 DateOnly/TimeOnly 查询参数?
- java - 如何理解 leecode 中的这种递归?
- bash - WSL bash,为每个可用的 Windows 驱动器创建别名
- r - 解释变量的 dwt 分解