class Bird(object):
def __init__(self, height, weight, has_feathers, capable_of_flying, bird_migrates, bird_sings, bird_eats_worms):
self.height = height
self.weight = weight
self.has_feathers = has_feathers
self.capable_of_flying = capable_of_flying
self.bird_migrates = bird_migrates
self.bird_sings = bird_sings
self.bird_eats_worms = bird_eats_worms
def get_height(self):
return self.height
def get_weight(self):
return self.weight
def get_has_feathers(self):
if self.has_feathers:
return "The bird has feathers"
else:
return "The bird does not have feathers"
# Etc...
A few things of note:
- You cannot have a function and variable of the same name, so I had to rename the functions to “get_…”
- If you want to make a function part of a class (called a method) then it has to be indented to be in the class.
- A class method needs to have the class object passed to it as the first parameter (called
self
by convention). This is how the class knows information about itself. - The variables in the class need to be accessed with
classvar.variable
, where inside the classclassvar
isself
. - CamelCase should only be used for class names in python. Use all_lower_case_and_underscore for variable and function names.
You would use the class like this:
penguin = Bird(10, 30, True, False, False, True, False)
print penguin.get_has_feathers() # "The bird has feathers"
The whole “get_…” paradigm is an “anti-pattern” in python (you might have a C++ background where this is considered the correct way to do it). It’s better to just expose the variables directly:
class Bird(object):
def __init__(self, height, weight, has_feathers, capable_of_flying, bird_migrates, bird_sings, bird_eats_worms):
self.height = height
self.weight = weight
if has_feathers:
self.has_feathers = "The bird has feathers"
else:
self.has_feathers = "The bird does not have feathers"
# etc...
penguin = Bird(10, 30, True, False, False, True, False)
print penguin.has_feathers # "The bird has feathers"
solved Class in Python [closed]