How should a python type hint require that a value has a given attribute?

前端 未结 3 1324
长情又很酷
长情又很酷 2021-01-03 09:31

Let\'s say I have a simple function like this:

def foo(a: Any):
    return a.bar + a.baz

I would lik

3条回答
  •  天涯浪人
    2021-01-03 09:44

    You need to create a class with those attributes so the object you pass has them in it. I.e.:

    class Myclass():
        def __init__(self, bar, baz):
            self.bar = bar
            self.baz = baz
    
    
    def foo(a: Myclass):
        return a.bar + a.baz
    

提交回复
热议问题