Im just try to build a basic class so that I can learn some more about python. So far I have the following :
class Bodymassindex:
count = 0
def __init__(self,name,weight,height):
self.name = name
self.weight = 14 * weight
self.height = 12 * height
notes = "no notes have been assigned yet"
bmitotal = 0
Bodymassindex.count += 1
def displayCount(self):
print "Total number of objects is %d" % Bodymassindex.count
def notesBmi(self,text):
self.notes = text
def calcBmi(self):
return ( self.weight * 703 ) / ( self.height ** 2 )
In terms of adding a note variable and viewing what is the correct way of doing so ?
Thanks,
2 Answers 2
The bmitotal and notes variables in __init__ will be local and garbage collected when __init__ finishes, so initializing them like that is useless. You probably want to initialize them as self.notes and self.bmitotal
Bodymassindex.count would be like a static variable, which shares its value with all the instances.
10 Comments
Bodymassindex.count can be reset on an instance...e.g. self.count = 5 which will not update the "static version".*like* a static variable ;) i didn't want to confuse him too much.self.count will point to Bodymassindex.count unless there is an instance variable called count, in which case it points to that.self.count means in the context of the program. If self.count doesn't exist as an instance variable, it means the static variable BodyMassIndex.count, otherwise it means the instance variable.Just access the attribute:
class BodyMassIndex(object): #Inheriting from object in 2.x ensures a new-style class.
count = 0
def __init__(self, name, weight, height):
self.name = name
self.weight = 14 * weight
self.height = 12 * height
self.notes = None
self.bmitotal = 0
BodyMassIndex.count += 1
def display_count(self):
print "Total number of objects is %d" % BodyMassIndex.count
def calculate_bmi(self):
return ( self.weight * 703 ) / ( self.height ** 2 )
test = BodyMassIndex("bob", 10, 10)
test.notes = "some notes"
print(test.notes)
There is nothing wrong with direct access in Python. As others have noted, it's likely you meant to make notes and bmitotal instance variables, which I have done here.
2 Comments
notes to None initially to make testing for the "no notes" case easier.
CapWordsfor class names andlowercase_with_underscoresfor function names. It's also worth noting that 'setters likenotesBmiare not worth using in Python - make it an attribute and use it like one. If you need to do something there later, useproperty().object... e.g.class Bodymassindex(object):