[英]VPython Inheritance
我目前正在嘗試創建一個類,其唯一目的是快速創建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 sphere()對象的原始屬性。 這實際上最初工作,對象渲染和變量添加。 但現在,我無法更改VPython對象。 如果我輸入:
Sphereobj.pos=(1,2,3)
該位置將更新為變量,但VPython不會更新渲染的對象。 現在對象和渲染對象之間存在脫節。 有沒有辦法在創建新對象時繼承VPython對象的呈現方面? 我不能簡單地使用
class Bsphere(sphere(pos=ObjPosition, radius=Rad,color=color.red)):
self.momentum=Momentum
關於VPython的文檔不多。
我不使用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
構造中聲明的所有參數。
from visual import *
class Physikobject(sphere):
def __init__(self):
sphere.__init__(self, pos = (0,0,0), color=(1,1,1))
self.otherProperties = 0
我覺得這個有幫助 - 問題可能是舊的,人們可能仍會考慮它。
我是一個很大的vpython用戶,我從來沒有使用過像這樣的東西,但我知道vpython已經有了你想要實現的功能。
===============================實施例================== ==================
from visual import *
myball = sphere()
myball.weight = 50
print (myball.weight)
此代碼創建一個球,然后初始化一個名為weight的變量,然后顯示它。
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一起玩得開心!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.