Last active
July 5, 2017 14:16
-
-
Save JokerMartini/3152f2e3bc4f8fb8eb19 to your computer and use it in GitHub Desktop.
Python: This example demonstrates overrides for class methods for testing == and !=
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Imports | |
# ------------------------------------------------------------------------------ | |
import sys | |
import uuid | |
# Class Object | |
# ------------------------------------------------------------------------------ | |
class Node(object): | |
def __init__(self, name="", age=None): | |
self.name = name | |
self.age = age | |
self.uid = str( uuid.uuid4( ) ) | |
def __eq__(self, other): | |
# return self.uid == other.uid | |
# return self.value == other.value | |
return isinstance(self, other.__class__) and self.uid == other.uid | |
def __ne__(self, other): | |
# return self != other | |
return not self.__eq__(other) | |
class Person(Node): | |
def __init__(self, name="", age=0 ): | |
super(Person, self).__init__(name=name, age=age) | |
class Kid(Node): | |
def __init__(self, name="", age=0 ): | |
super(Kid, self).__init__(name=name, age=age) | |
A = Person("Jeff") | |
B = Person("Mindy") | |
C = A | |
D = Kid("Doug") | |
print "Should be True:", A == C | |
print "Should be False:" , A != C | |
print "Should be False:" , A == B | |
print "Should be True:", A != B | |
print "Should be False:", A == D | |
print "Should be True:" , A != D | |
print "Should be False:" , D != D | |
print A.uid | |
print hash(A.uid) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import copy | |
import uuid | |
# Classes | |
class Node(object): | |
def __init__(self, name): | |
self.name = name | |
self.uid = str( uuid.uuid4( ) ) | |
def copy_node(self): | |
new_node = copy.deepcopy( self ) | |
new_node.uid = str( uuid.uuid4( ) ) | |
return new_node | |
class Truck(Node): | |
def __init__(self, name=""): | |
super(Truck, self).__init__(name=name) | |
old_truck = Truck( name="Tonka Truck") | |
new_truck = old_truck.copy_node() | |
print old_truck.uid | |
print new_truck.uid |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment