I'm trying to create a class that will create objects with different methods based on an input. The point of this is to avoid using an if statement every time the method is called.
Below is the code I thought would work, but isn't working.
class Food:
def __init__(self,food_type):
self.food_type = food_type
if food_type == 'cookie':
print 'this is a cookie'
def is_awesome(self):
print "is awesome"
else:
print 'this is not a cookie'
def is_awesome(self):
print "not awesome"
Oreo = Food('cookie')
Oreo.is_awesome()
The code doesn't error on the def is_awesome(self)
statement, but instead the Oreo.is_awesome()
line raises the error:
"AttributeError: Food instance has no attribute is_awesome".
Is there a better way to make objects with different methods? and is there a reason why the method is_awesome
isn't callable by 'Oreo.is_awesome'?
Is there a better way to make objects with different methods?
Yes a way that works :) Polymorphism is a great candidate.
class Food:
def is_awesome(self):
print 'not awesome'
class Cookie(Food):
def is_awesome(self):
print 'is awesome'
and is there a reason why the method is_awesome isn't callable by 'Oreo.is_awesome'?
Yes, it's not bound to the instance (conventionally called self
) in any
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments