【问题标题】:VPython InheritanceVPython 继承
【发布时间】:2013-04-11 04:15:49
【问题描述】:

我目前正在尝试创建一个类,其唯一目的是快速创建 VPython 对象并将附加值附加到该对象。 VPython 会自动创建一个具有位置和尺寸等值的对象。但是,我还想添加变量,例如材料的物理特性和动量。所以这是我的解决方案:

class Bsphere(physicsobject):

     def build(self):

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

物理对象看起来像这样:

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 的文档并不多。

【问题讨论】:

    标签: python object inheritance 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 构造中声明的所有参数。

    【讨论】:

    • 我建议您阅读来自learnpythonthehardway 的关于继承的教程,尤其是覆盖。理解这些概念非常重要,可以帮助您避免以后出现错误。
    【解决方案2】:
    from visual import *
    class Physikobject(sphere):
        def __init__(self):
            sphere.__init__(self, pos = (0,0,0), color=(1,1,1))
            self.otherProperties = 0
    

    我认为这个有帮助 - 这个问题可能已经过时了,人们可能还在考虑它。

    【讨论】:

      【解决方案3】:

      我是一个大的 vpython 用户,我从来没有使用过这样的东西,但我知道 vpython 已经有你想要实现的功能。
      ================================示例================== ==================

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

      此代码创建一个球,然后初始化一个名为 weight 的变量,然后显示它。

      【讨论】:

        【解决方案4】:

        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 的乐趣!

        【讨论】:

          猜你喜欢
          • 2015-04-19
          • 2012-10-30
          • 2017-12-27
          • 2014-02-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多