2012-04-26 20 views
1

私はPythonについてもっと学ぶことができるように基本クラスを構築しようとしています。 は、これまでのところ私は、次のしている:基本的なPythonクラス

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) 

ノート変数を追加し、そうするのが正しい方法は何か見るの面では? __init__

おかげで、

+6

[PEP-8](http://www.python.org/dev/peps/pep-0008/)は、クラス名に '' CapWords''を、関数名に '' lowercase_with_underscores''を示唆しています。 'notesBmi'のような' settersはPythonで使う価値がないことに気付く価値があります - それを属性にして、それを一つのように使うこと。後で何かする必要がある場合は、['' property() ''](http://docs.python.org/library/functions.html#property)を使用してください。 –

+2

Python 2.xを使用する場合、 'object'から継承することが望ましい場合があります。 'クラスBodymassindex(オブジェクト):' – mgilson

+1

@mgilson:*頻繁に*?常に*望ましい*です。 –

答えて

2

だけで属性にアクセス:

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) 

Pythonで直接アクセスは何も問題はありません。他の人が指摘しているように、私がここで行ったnotesbmitotalのインスタンス変数を作ったのかもしれません。

+3

最初に「ノート」を「なし」に設定して、「ノートなし」のケースを簡単にテストする方が良いかもしれません。 –

+1

@larsmansこれは良いアドバイスです、私は単にOPがしたことに固執していました。編集されました。 –

4

bmitotalnotes変数がローカルになり、それは無用であるよう__init__仕上げなので、それらを初期化するときにごみを収集します。あなたは、おそらくself.notesself.bmitotal

Bodymassindex.countは、すべてのインスタンスでのような静的変数、株式その値になるようにそれらを初期化したいです。

+0

また、Bodymassindex.countはインスタンス上でリセットすることができます。 'self.count = 5'は"静的バージョン "を更新しません。 – mgilson

+0

はい、そういうわけで私は静的変数と同じように言っていました;)私は彼をあまりにも混乱させたくありませんでした。 – KurzedMetal

+2

@mgilsonこれは真実ではありません。リセットされず、カウントと呼ばれるインスタンス変数がない限り、 '' self.count''は '' Bodymassindex.count''を指します。 –