我希望使用typing.Optional将可选参数继承到另一个Python类,但不能在子类中设置该属性。
我有两个类:父类测试和子类Test_inherit。
在父类测试中,我使用typing.Optional定义了一个可选的参数/方法/属性。
如果我在父类中使用这个可选参数,一切都很好。但是,如果我将这个类继承到另一个Test_inherit,则无法定义这个可选参数。
有办法这样做吗?
提前谢谢。
from typing import Optional
from typing import get_type_hints
class Test:
name: str
type: str
units: Optional[str]
def __init__(self,name,typ_,**kwargs)-> None:
self.name = name
self.type = typ_
#self.units = None
type_hints = get_type_hints(self)
for argname in kwargs:
#print(argname)
type_hint = type_hints[argname]
if hasattr(type_hint, "__args__"): # For the Optional[...] types
type_hint = next(t for t in type_hint.__args__
if not isinstance(t, type(None)))
setattr(self, argname, type_hint(kwargs[argname]))
class Test_inherit(Test):
TAG: str
symbol: Optional[str]
def __init__(self,name,typ_,**kwargs)-> None:
self.TAG='Test_tag'
super().__init__(name, typ_, **kwargs)
test0=Test('hallo','float')
print(test0.name,test0.type)
test1=Test('hallo','float',units='N')
print(test1.name,test1.type,test1.units)
test2_0=Test_inherit('hallo','float')
print(test2_0.name,test2_0.type)
test2_1=Test_inherit('hallo','float',symbol='N')
print(test2_1.name,test2_1.type,test2_1.symbol)
test3=Test_inherit('hallo','float',units='N')
print(test3.name,test3.type,test3.units)发布于 2022-08-29 12:36:33
在python提示中,Optional意味着变量/属性为or或类型。
来自文档
typing.Optional可选类型。Optional[X]等同于X | None(或Union[X, None])。 请注意,这与可选参数的概念不同,可选参数是一个默认参数。带有默认值的可选参数不需要其类型注释上的可选限定符,因为它是可选的。例如: def (arg: int = 0) ->无:. 另一方面,如果允许显式值None,则使用可选参数是适当的,无论参数是否为可选参数。例如: def foo(arg: Optionalint = None) -> None:.
发布于 2022-08-29 13:22:17
这似乎很管用。我已经把这一行从
type_hints = get_type_hints(self))至
type_hints = get_type_hints(type(self))from typing import Optional
from typing import get_type_hints
class Test:
name: str
type: str
units: Optional[str]
def __init__(self,name,typ_,**kwargs)-> None:
self.name = name
self.type = typ_
#self.units = None
type_hints = get_type_hints(type(self))
for argname in kwargs:
#print(argname)
type_hint = type_hints[argname]
if hasattr(type_hint, "__args__"): # For the Optional[...] types
type_hint = next(t for t in type_hint.__args__
if not isinstance(t, type(None)))
setattr(self, argname, type_hint(kwargs[argname]))
class Test_inherit(Test):
TAG: str
symbol: Optional[str]
def __init__(self,name,typ_,**kwargs)-> None:
self.TAG='Test_tag'
super().__init__(name, typ_, **kwargs)https://stackoverflow.com/questions/73527935
复制相似问题