繁体   English   中英

VPython继承

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM