0

I'm using the DroneKit API in Python for controlling a drone using a companion computer. I'm trying to create a class, Vehicle, which inherits from the Vehicle class in DroneKit. The purpose of this class is for me to override some methods present in DroneKit that don't work with PX4 as well as adding a few methods of my own, whilst still having access to all of the methods available by default.

The issue is that you don't create a Vehicle object directly using Dronekit – you call the connect() function which return a Vehicle object.

My question is, how do I create an instance of my class?

The accepted method seems to be to call the parent init(), like so:

class Vehicle(dronekit_Vehicle):
    def __init__(self, stuff):
        dronekit_Vehicle.__init__(stuff)

But like I said, you don't create a Vehicle object directly in Dronekit, e.g. vehicle = Vehicle(stuff), but by vehicle = connect(stuff), which eventually returns a Vehicle object but also does a bunch of other stuff.

The only way I can think of is

class Vehicle(dronekit_Vehicle):
    def __init__(self, stuff):
        self.vehicle = connect(stuff)

And then having to use self.vehicle.function() to access the default DroneKit commands and attributes, which is a huge pain.

How do I make this work?

4

1 回答 1

2

对象的定义方式与connect. 调用connect只是一些方便的函数,它围绕对象创建包装了一些逻辑:

def connect(...):
    handler = MAVConnection(...)
    return Vehicle(handler)

Vehicle.__init__()定义为

def __init__(self, handler):
    super(Vehicle, self).__init__()
    self._handler = handler
    ...

因此,只要您在构造函数中传递处理程序:

class MyVehicle(dronekit.Vehicle):
    def __init__(self, handler):
      super(MyVehicle, self).__init__(handler)

您的班级将与connect()

connect(..., vehicle_class=MyVehicle)
于 2018-01-24T12:55:52.527 回答