0

In Python I'm making a graph class which I intend to design by creating a Node class, and then an Edge class which takes as arguments to the constructor two nodes, a source and target. I'd also like to check in the Edge class that the two inputs are in fact Nodes, so I'd like to include some lines like

assert type(src) is Node and type(tgt) is Node 

However, this will not act as I expect it to. As I understand it, I would need to use something like src.__name__ is Node.__name__ but this just seems ugly. Is there a way to control the type name of a user-defined class so that the code reads a little more nicely?

I tried following some of what I found here: Python: Change class type name

and wrote the code

class Node: ... __class__ = type("Node", (type,), {}) 

I'm not sure if I was mis-applying the lessons found in that link or if those lessons wouldn't accomplish what I'm trying to do--but one way or another, it didn't do what I was hoping for.

2
  • 2
    Why doesn't type(src) is Node work? Commented Aug 14, 2018 at 2:27
  • assert type(src) is Node and type(tgt) is Node should work, how does it not work for you? Commented Aug 14, 2018 at 2:49

1 Answer 1

2

Check out "isinstance" built-in function: https://docs.python.org/2/library/functions.html#isinstance

Example:

>>> class Node(object): ... pass ... >>> class Booger(object): ... pass ... >>> n=Node() >>> b=Booger() >>> isinstance(n, Node) True >>> isinstance(b, Node) False >>> >>> class SubNode(Node): ... pass ... >>> sn=SubNode() >>> isinstance(sn, Node) True 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.