首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python:继承typing.Optional参数

Python:继承typing.Optional参数
EN

Stack Overflow用户
提问于 2022-08-29 11:13:00
回答 2查看 48关注 0票数 0

我希望使用typing.Optional将可选参数继承到另一个Python类,但不能在子类中设置该属性。

我有两个类:父类测试和子类Test_inherit。

在父类测试中,我使用typing.Optional定义了一个可选的参数/方法/属性。

如果我在父类中使用这个可选参数,一切都很好。但是,如果我将这个类继承到另一个Test_inherit,则无法定义这个可选参数。

有办法这样做吗?

提前谢谢。

代码语言:javascript
复制
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)
EN

回答 2

Stack Overflow用户

发布于 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:.

票数 1
EN

Stack Overflow用户

发布于 2022-08-29 13:22:17

这似乎很管用。我已经把这一行从

代码语言:javascript
复制
type_hints = get_type_hints(self))

代码语言:javascript
复制
type_hints = get_type_hints(type(self))
代码语言:javascript
复制
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)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73527935

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档