首页 > 解决方案 > 更改继承成员的提示类型

问题描述

假设我有一个类的类型提示成员,当我继承时,我想将该成员的提示类型更改为继承类型。那可能吗?

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.

标签: pythonpython-3.xinheritancewarningstype-hinting

解决方案


尽管PEP 526明确提到__init__允许在其中注释实例变量,但这似乎在 PyCharm 中不起作用。不过,它在 mypy 0.761 上运行良好。所以我想这是一个 PyCharm 特有的问题。

除了注释之外,__init__还可以在类主体本身中注释实例变量(再次参见PEP 526)。这确实适用于 PyCharm。因此,为了解决您的问题,您可以使用:

class Kenel(Home):
    occupant: Dog

    def __init__(self, occupant: Dog):
        super().__init__(occupant)

推荐阅读