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
-
And if node1 and node2 are not Nodes, what should happen?Kevin– Kevin2016年11月28日 13:25:11 +00:00Commented Nov 28, 2016 at 13:25
-
Note that while python has definitely the tools to do proper type checking, it could be unnecessary to do it depending on your particular application. Remember that python does dynamic typing: better ask for forgiveness than permission.farsil– farsil2016年11月28日 13:30:50 +00:00Commented Nov 28, 2016 at 13:30
2 Answers 2
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.
Comments
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