Felix Brasseur
Felix Brasseur

Reputation: 3

Creating objects in a class in Python

Is it possible to create an object of a class using objects of another class, for example:

class Node(object):

    def __init__(self, name):
        self.name = name

class Edge(object):

    def __init__(self, name, node1, node2):
        self.name = name
        self.node1 = node1 #only if it is an object of Node
        self.node2 = node2 #only if it is an object of Node

Hence an object of Edge will only be created if both node1 and node2 are objects of Node. Thanks

Upvotes: 0

Views: 58

Answers (2)

Kevin
Kevin

Reputation: 76184

You can verify the objects' types and raise an exception if they aren't what you want:

def __init__(self, name, node1, node2):
    if not isinstance(node1, Node):
        raise ValueError("Expected node1 to be a Node")
    if not isinstance(node2, Node):
        raise ValueError("Expected node2 to be a Node")
    self.name = name
    self.node1 = node1 #only if it is an object of Node
    self.node2 = node2 #only if it is an object of Node

However, doing this kind of type checking is somewhat in opposition to the "we're all adults here" philosophy that is popular in the Python community. You should trust your users to provide an object whose interface is satisfactory for the tasks it needs to perform, regardless of whether it actually inherits from Node. And your users should understand that if they fail to uphold the implied interface contract, then it's their own fault and they shouldn't come crying to you.

Upvotes: 2

harshil9968
harshil9968

Reputation: 3244

use this article to check if object is of given class

class Node(object):

    def __init__(self, name):
        self.name = name

class Edge(object):

    def __init__(self, name, node1, node2):
        self.name = name
        if isinstance(node1, Node):
            self.node1 = node1 #only if it is an object of Node
        else:
            raise ValueError("Expected node1 to be a Node")
        if isinstance(node2, Node):
            self.node2 = node2 #only if it is an object of Node

Upvotes: 0

Related Questions