Pycharm静态分析并没有如我所愿推断子类类型

问题描述 投票:0回答:1

在下面的Python代码中,

TruckDriver
类继承自
Driver
类,
Truck
类继承于
Vehicle
类。

driver
类的
Truck
属性是
TruckDriver
类型(在类型提示中指定),并传递给
Vehicle
类的构造函数(接受通用
Driver
类型) .

但是,Pycharm 在

Truck
类中警告我
driver
不具有
TruckDriver
特定属性。具体来说,它在
company
行中强调了
print(f"Company: {self.driver.company}")
属性,并带有以下警告:

“Driver”类的未解析属性引用“company”

有什么方法可以解决此类警告吗?我还在我的项目中使用 Ruff 作为 linter,但它在这里似乎没有帮助。

class Driver:
    def __init__(self, name: str):
        self.name = name

class TruckDriver(Driver):
    def __init__(self, name: str, company: str):
        super().__init__(name)
        self.company = company

class Vehicle:
    def __init__(self, driver: Driver):
        self.driver = driver

    def drive(self):
        print(f"{self.driver.name} is driving.")

class Truck(Vehicle):
    def __init__(self, driver: TruckDriver):
        super().__init__(driver)

    def drive(self):
        super().drive()
        print(f"Company: {self.driver.company}")
python inheritance pycharm static-analysis
1个回答
1
投票

使用通用车辆:

from typing import Generic, TypeVar

D = TypeVar("D", bound="Driver")

class Driver:
    def __init__(self, name: str):
        self.name = name

class TruckDriver(Driver):
    def __init__(self, name: str, company: str):
        super().__init__(name)
        self.company = company

class Vehicle(Generic[D]):
    def __init__(self, driver: D):
        self.driver = driver

    def drive(self):
        print(f"{self.driver.name} is driving.")

class Truck(Vehicle[TruckDriver]):
    def __init__(self, driver: TruckDriver):
        super().__init__(driver)

    def drive(self):
        super().drive()
        print(f"Company: {self.driver.company}")

alice = Driver("Alice")
carol = TruckDriver("Carol", "Acme Truck Co.")

car = Vehicle(alice)
truck = Truck(carol)

car.drive()
truck.drive()
© www.soinside.com 2019 - 2024. All rights reserved.