-2

I'm writing code that has two classes. The one class creates text elements for a 3-D environment. The other will group them together in that environment. What I'm trying to do is have the second class call instances of the first class. In other words, in def makeGroup I want to be able to call an instance of class msg. How would the coding be worded? Currently, the first class is inherited into the second, and then I'm trying to call the object self.text, but I don't know how I should refer to it. I don't believe I'm quite using inheritance correctly.

class msg:
    def __init__(self,num,unit):
        self.message = str(num) + ' ' + unit
        self.num = num
        self.text = viz.addText(self.message)

class msgGroup(msg):
    def __init__(self,x,y,z):
        self.msgLs=[]
        self.ghostMsg= viz.addText('',pos=[x,y,z],color= [0.000, .9, 0.071])
        self.msgLs.append(self.ghostMsg)

    def makeGroup(self):
        msg.text.setPosition([0,(len(self.msgLs)-1)*-1.5,0], viz.REL_PARENT)
        self.msgLs.append(msg.text)
4

2 に答える 2

2

5つのこと:

  1. これがPython2の場合、msgクラスはから継承する必要がありますobject
  2. PEP8:これに従わないと、誰もあなたのコードをフォローできなくなります
  3. msgGroupから継承する場合msg、すべてmsgGroupのインスタンスには、のインスタンスが持つすべてのメンバー(データ、メソッド、およびよりエキゾチックなもの)も含まれますmsg。メソッドmakeGroupで、現在のインスタンスのtextメンバーを参照するには、を実行しますself.text
  4. おそらく、それぞれmsgGroupにいくつかmsgのを持たせたいでしょう。これを行うには、継承を使用せずに、sのmsgGroupリストをmsg用意して、それを繰り返し処理します。

    for msg in self.msg_list:
        print msg.text
    
  5. オブジェクトまたはクラスのメンバーを参照することは、「それを呼び出す」とは呼ばれません。演算子を使用して、関数、メソッド、およびその他の呼び出し可能オブジェクト(クラスなど)を呼び出し()ます。

    foo = self.makeGroup # assigning makeGroup to a variable
    bar = self.makeGroup() # calling makeGroup, then assigning the result of that call to a variable
    
于 2012-07-20T18:12:55.433 に答える
2

いいえ、あなたは確かに継承を誤解しています。継承は、クラスBがクラスAとすべて同じプロパティを共有しているが、さらにいくつか、おそらくより具体的なプロパティを持っている場合に使用されます。たとえば、人は人です。

あなたのケースは異なります:あなたにはグループがあり、グループにはメッセージがあります。これは構成であり、継承ではありません。「is-a」ではなく「has-a」です。内にmessage_listを定義し、msgGroupそれにメッセージを追加するだけで、メッセージを繰り返し処理してそのtext属性にアクセスできます。

于 2012-07-20T18:08:27.393 に答える