2013-04-11 14 views
3

我正在嘗試創建一個類,以便快速創建VPython對象並將附加值附加到對象。 VPython自動創建一個具有位置和維數等值的對象。但是,我也想添加變量,如物質的物理屬性和動量。因此,這裏是我的解決方案:VPython繼承

class Bsphere(physicsobject): 

    def build(self): 

     sphere(pos=ObjPosition, radius=Rad,color=color.red) 

隨着physicsobject看起來像這樣:

class physicsobject: 

    def __init__(self): 

     self.momentum=Momentum 

從本質上講,我想這仍然保留VPython領域的原始性()對象,同時增加新的變數。這實際上起作用,對象呈現和變量被添加。但是現在,我無法改變VPython對象。如果我輸入:

Sphereobj.pos=(1,2,3) 

該位置將更新爲變量,但是,VPython不會更新呈現的對象。現在對象和渲染對象之間存在斷開。有什麼方法可以在創建新對象時繼承VPython對象的渲染方面?我不能簡單地用

class Bsphere(sphere(pos=ObjPosition, radius=Rad,color=color.red)): 

    self.momentum=Momentum 

並沒有對VPython多文檔。

回答

1

我不使用VPython。但是,從它的外觀來看,您繼承了physicsobject的財產,而不是sphere。我的建議是嘗試這個辦法:

# Inherit from sphere instead 
class Bsphere(sphere): 
    # If you want to inherit init, don't overwrite init here 
    # Hence, you can create by using 
    # Bpshere(pos=ObjPosition, radius=Rad,color=color.red) 
    def build(self, material, momentum): 
     self.momentum = momentum 
     self.material = material 

然後,您可以使用:

myobj = Bsphere(pos=(0,0,0), radius=Rad,color=color.red) 
myobj.pos(1,2,3) 

不過,我建議overwrite__init__方法在你的子類,提供你知道所有的參數在原sphere構建申報。

+0

謝謝,現在似乎工作。 – user1453064 2013-04-12 03:57:52

+1

我建議你閱讀繼承的[learnpythonthehardway](http://learnpythonthehardway.org/book/ex44.html)的教程,特別是覆寫。這些概念對理解非常重要,並且可以幫助您在以後避免錯誤。 – nqngo 2013-04-12 13:22:47

0
from visual import * 
class Physikobject(sphere): 
    def __init__(self): 
     sphere.__init__(self, pos = (0,0,0), color=(1,1,1)) 
     self.otherProperties = 0 

我認爲這一個有幫助 - 問題可能是老的人們可能仍然會考慮它。

0

我是一個很大的vpython用戶,我從來沒有使用過這樣的東西,但我知道vpython已經有了你試圖實現的功能。
===============================示例================ ====================

from visual import * 
myball = sphere() 
myball.weight = 50 
print (myball.weight) 

此代碼創建一個球然後初始化一個稱爲加權變量然後顯示它。

0

關於VPython的美妙之處在於您不需要那樣做。

VPython爲您做到了!

這是所有你需要做的:

variable_name = sphere()#you can add pos and radius and other things to this if you want 
variable_name.momentum = something 

您可以輕鬆地插入到這個函數:

objectstuffs = [] 
def create_object(pos,radius,color,momentum): 
    global objectstuffs 
    objectstuffs.append(sphere(pos=pos,radius=radius,color=color)) 
    objectstuffs[len(objectstuffs)-1].momentum = momentum 

該函數絕對不是在所有情況下使用的最好的事情,但您可以輕鬆編輯該功能,這僅僅是爲了舉例。

與VPython玩得開心!