Skip to main content
 首页 » 编程设计

python之是否可以在类中添加静态类型

2025年05月04日16jillzhang

我正在努力做到这样,当我设置一个变量时,当我拼错它时会出现编译类型错误。到目前为止,在我所有的尝试中,变量刚刚被创建。

我不介意将变量放在类、模块、字典或任何组合中。我只想在拼写错误时出现编译时错误

这是一个例子:

class Foo: 
   bar="" 
   def __init__(self,bar_value): 
     self.barr=bar_value # want syntax error here 
the_foo=Foo("hellow") 

编辑:我的术语有误:我的意思是静态打字

请您参考如下方法:

Python 是强类型的 - 使用类最接近的是使用 __slots__ 限制属性创建,例如:

class Foo(object): 
    __slots__ = ['bar'] 
    def __init__(self, bar_value): 
        self.barr = bar_value 
 
the_foo = Foo('bar value') 
# AttributeError: 'Foo' object has no attribute 'barr' 

有关 Python Data model 中插槽的更多信息

TL;DR: 可以为此类变量分配一个字符串、可迭代对象或具有实例使用的变量名称的字符串序列。如果在新式类中定义,__slots__ 为声明的变量保留空间并防止为每个实例自动创建 __dict__ 和 __weakref__。