Jan-03-2019, 11:43 AM
Jan-03-2019, 01:47 PM
Do you mean overloading functions by it's call signature?
Sometimes it's useful to have one function, which depends on input type.
https://docs.python.org/3/library/functo...ledispatch
I never used it in real applications.
Another cool feature are the magic methods. You control the behavior of an object.
But I guess this does not answer your question.
Sometimes it's useful to have one function, which depends on input type.
https://docs.python.org/3/library/functo...ledispatch
I never used it in real applications.
Another cool feature are the magic methods. You control the behavior of an object.
But I guess this does not answer your question.
class Nodes: def __init__(self): self.nodes = [] def copy(self): new_nodes = self.__class__() new_nodes.extend(self.nodes) return new_nodes def add(self, node): self.nodes.append(node) def extend(self, nodes): self.nodes.extend(nodes) def __getitem__(self, index): return self.nodes[index] def __setitem__(self, index, node): self.nodes[index] = node def __delitem__(self, index): del self.nodes[index] def __len__(self): return len(self.nodes) def __iter__(self): for node in self.nodes: yield node def __eq__(self, other): return self.nodes == other.nodes def __repr__(self): return '{}(nodes={})'.format(self.__class__.__name__, len(self)) nodes = Nodes() nodes.add('Baz') nodes.add('Foo') other_nodes = nodes.copy()This class supports:
- get a node by it's index value:
node[0]
- assign a node to an index:
nodes[0]='Foo'
- delete items:
del nodes[0]
- getting the count of nodes:
len(nodes)
- equality check:
nodes == new_nodes
- representation of the object:
print(nodes)
- sorting, because __iter__or __len__ and __getitem__ is supported.
Jan-04-2019, 12:03 PM
To compare two objects, we can overload operators in Python. We understand 3>2. But what is orange>apple? Let’s compare apples and oranges now.
>>> class fruit: def __init__(self,type,size): self.type='fruit' self.type=type self.size=size def __gt__(self,other): if self.size>other.size: return True return False >>> orange=fruit('orange',7) >>> apple=fruit('apple',8) >>> apple>orange True >>> orange>apple False
Jan-04-2019, 12:23 PM
Please use python and output tags when posting code and results. Here are instructions on how to use them.