user3889486
user3889486

Reputation: 656

In python, how to force a function argument to be of a specific Class

In the following example

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

I want to do something like B.__init__(self, a:A) so that the argument in class B is an object of A.

Upvotes: 1

Views: 1170

Answers (1)

Rahul Goswami
Rahul Goswami

Reputation: 595

You can always raise a 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

Upvotes: 1

Related Questions