【问题标题】:In python, how to force a function argument to be of a specific Class在python中,如何强制函数参数属于特定类
【发布时间】:2018-07-12 14:46:20
【问题描述】:

在下面的例子中

class A():
    def __init__(self):
        self.foo = 'foo'

class B():
    def __init__(self, a):
        self.a = a

a = A()
B(a)    # right
B('a')  # wrong

我想做类似B.__init__(self, a:A) 的事情,这样B 类中的参数就是A 的对象。

【问题讨论】:

  • 有很多方法,例如Rahul Goswami 在下面的回答向您展示,但总的来说,这在 Python 中被认为有点反模式:传递的参数应该没问题,只要它可以做您需要做的事情(鸭子打字),而不是匹配您之前定义的类。作为一种折衷方案,您可以使用新的type hinting 来推荐您的课程。
  • 这正是我想要的

标签: python python-3.x parameter-passing


【解决方案1】:

您可以随时提出ValueError

class B():
    def __init__(self, a: A):
        if not isinstance(a, A):
            raise ValueError("a must an object of class A")
        self.a = a

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-29
    • 1970-01-01
    • 2020-05-12
    • 1970-01-01
    • 2017-05-05
    • 2018-08-27
    • 2020-04-04
    • 1970-01-01
    相关资源
    最近更新 更多