Skip to content

Instantly share code, notes, and snippets.

@dmikurube
Created January 24, 2014 06:31
Show Gist options
  • Save dmikurube/8592959 to your computer and use it in GitHub Desktop.
Save dmikurube/8592959 to your computer and use it in GitHub Desktop.
class Shape(object):
def __new__(cls, desc, color='black'):
if cls is Shape:
if desc == 'sankaku':
return super(Shape, cls).__new__(Triangle, color)
elif desc == 'shikaku':
return super(Shape, cls).__new__(Rectangle, color)
else:
return super(Shape, cls).__new__(Shape, color)
else:
return super(Shape, cls).__new__(cls, desc, color)
def __init__(self, desc, color='black'):
print "__init__ is called. desc = %s. color = %s" % (desc, color)
self.desc = desc
@property
def number_of_edges(self): return 0
class Triangle(Shape):
@property
def number_of_edges(self): return 3
class Rectangle(Shape):
@property
def number_of_edges(self): return 4
instance1 = Shape('sankaku')
print 'number_of_edges = %d' % instance1.number_of_edges
print type(instance1)
print ''
instance2 = Shape('shikaku', 'red')
print 'number_of_edges = %d' % instance2.number_of_edges
print type(instance2)
print ''
instance3 = Shape('foo', 'blue')
print 'number_of_edges = %d' % instance3.number_of_edges
print type(instance3)
@dmikurube
Copy link
Author

init is called. desc = sankaku. color = black
number_of_edges = 3
class 'main.Triangle'

init is called. desc = shikaku. color = red
number_of_edges = 4
class 'main.Rectangle'

init is called. desc = foo. color = blue
number_of_edges = 0
class 'main.Shape'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment