在类python3中有多个类?

时间:2018-04-18 15:50:25

标签: python python-3.x class

我想做这样的事情:

Robot.GyroController.getLatestMeasurement()

有办法做到这一点吗? 更具体地说,我想这样做:

robot = Robot.__init__(arguments)
latesMeasurement = robot.GyroController.getLatestMeasurement()

这是有效的python吗?最重要的是,是否可以这样做?

我需要参加乐高比赛。我可以使用我想要的任何编程语言,所以我想我写一个库来获得比现有的更好的抽象(也是为了练习python,因为我想进入tensorflow)

我有一个叫做机器人的课程。该类初始化时引用了机器人具有的所有电机/传感器。

从那里,我想要一些可以控制电机,传感器和其他一些奇特东西的子类(或者其他什么?)。

每次我使用电机/传感器时,我都没有通过机器人(包含对电机/传感器的引用),而是认为我可以做这样的事情。

PS。我来自OOP,还在学习python,所以请,我打算尽可能地改进这个问题。请给我一个机会。

1 个答案:

答案 0 :(得分:0)

根据我的阅读,你想拥有一个拥有多个Motor类或类似东西的机器人类,也许这可以作为一个暗示如何做到这一点:

 class MotorController:
      def __init__(self):
          pass

      def goStraight():
          pass


 class Robot:
        def ___init___(self):
            self.motor_controllers = [] #List for storing all motors

        def add_motor_reference(self, reference):
            self.motor_controllers.append(MotorController(reference)) 
            #Appends new motors to the list

        def go_straight(self):
            for motor_controller in self.motor_controllers:
                motor_controller.goStraight()
            #Executes for the "goStraight" function on every motor in the list

这是一个虚拟的示例,说明如果您想要面向对象,您的代码可能会是什么样子。

修改     假设您已经拥有“MotorController”类

 class Robot:
        def ___init___(self, *args):
            self.motor_controllers = [] #List for storing all motors
            for motor in args:
                self.motor_controllers.append(MotorController(motor))
            #Here every motor reference you pass will be automatically added in the list of motor controllers.

修改 如果要在类的构造函数中添加电机,可以执行以下操作:

for city, extras in cities.items():
    print("\nInfo about the city " + city.title() + ":")
    for key, value in extras.items():
        try:
            if key == 'country':
                print(key.capitalize() + ": " + value.title())
            else:
                print(key.capitalize() + ": " + value)
        except(TypeError, AttributeError):
            print(key.capitalize() + ": " + str(value))