我的任务是在 Google Colab 上创建
class
。
这是我创建的代码:
from _typeshed import Self
class Customers:
greeting = 'Welcome to the Coffee Palace!'
def __init__(self, name, beverage, food, total):
self.name = name
self.beverage = beverage
self.food = food
self.total = total
c1 = Customers()
c2 = Customers()
c1.name = 'Samirah'
c1.beverage = 'Iced caffe latte'
c1.food = 'Cinnamon roll'
c1.total = 225
c2.name = 'Jerry'
c2.beverage = 'Caramel macchiato'
c2.food = 'Glazed doughnut'
c2.tota = 230
print('Samirah wants to drink '+ c1.beverage)
print('Jerry wants to eat '+ c2.food)
但是这个错误不断出现:
ModuleNotFoundError Traceback (most recent call last)
<ipython-input-13-d30ac4e0ffe7> in <module>()
----> 1 from _typeshed import Self
2 #CodeHere
3 class Customers:
4 greeting = 'Welcome to the Coffee Palace!'
5
ModuleNotFoundError: No module named '_typeshed'
我不知道如何解决这个问题,或者我的代码中是否确实存在一些错误。
typeshed stdlib 仅可用于类型检查,因此我们需要使用
TYPE_CHECKING
: 来保护导入
if typing.TYPE_CHECKING:
from _typeshed import ...
在 OP 的例子中,看起来他们实际上并不打算使用 typeshed,这可能就是为什么他们的示例没有意义(
Self
仅适用于元类)。
就我而言,我尝试使用
FileDescriptorOrPath
,这个构造在 python 3.12.1 和 mypy 1.10.0 中对我有用:
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from _typeshed import FileDescriptorOrPath
def read(path_or_buffer: "FileDescriptorOrPath", ...) -> str:
# ^ normally needs to be quoted
如果不想引用类型,还需要导入以后的注解:
from __future__ import annotations
...
def read(path_or_buffer: FileDescriptorOrPath, ...) -> str:
# ^ can be unquoted if using future annotations