1

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,

4

2 回答 2

4

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.

于 2012-04-26T13:04:30.330 回答
2

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.

于 2012-04-26T13:05:37.307 回答