简体   繁体   English

用相同的名称添加类内实例的所有变量

[英]Add all variables of instances within class with the same name

I have a class named Robot , which creates a number of instances of the classes Segment and Pointmass . 我有一个名为Robot的类,它创建了SegmentPointmass类的许多实例。 All these instances have a variable mass . 所有这些实例的mass都是可变的。 How can I obtain the total mass of all the objects within the object with the same variable name mass ? 如何获得具有相同变量名称mass的对象中所有对象的总mass

What I do right now: 我现在正在做什么:

class Robot:
    def __init__(self, massJoint1, massJoint2, massJoint3, massSlide, reachSlide, massArm, lengthArm):
        self.joint1 = Pointmass(massJoint1)
        self.joint2 = Pointmass(massJoint2)
        self.joint3 = Pointmass(massJoint3)

        self.slide = Slide(massSlide, reachSlide)
        self.arm = Arm(massArm, lengthArm)

        self.totalmass = self.joint1.mass + self.joint2.mass + self.joint3.mass + self.slide.mass + self.arm.mass

    def printVars(self):
        attrs = vars(self)
        print(', \n'.join("%s: \t%s" % item for item in attrs.items()))
        print()


class Pointmass:
    def __init__(self, mass):
        self.mass = mass

        self.location = None


class Segment:
    def __init__(self, mass):
        self.mass = mass

        self.start = None
        self.end = None

In which 在其中

self.totalmass = self.joint1.mass + self.joint2.mass + self.joint3.mass + self.slide.mass + self.arm.mass

is a very long line, and is really inconvenient when the Robot gains more arms and joints... Is there a better way to obtain the total mass? 这是一条很长的线,当Robot获得更多的手臂和关节时真的很不方便...是否有更好的方法来获取总质量?

You shouldn't be storing the joints in separate attributes. 您不应该将关节存储在单独的属性中。 Rather, store a simple joints list; 而是存储一个简单的joints列表; then you can simply use sum with a generator expression. 那么您可以简单地将sum与生成器表达式一起使用。

self.totalmass = sum(j.mass for j in self.joints)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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