[英]Creating a subclass without direct access to the parent class __init__() function
I'm using the DroneKit API in Python for controlling a drone using a companion computer. 我正在Python中使用DroneKit API来使用配套计算机来控制无人机。 I'm trying to create a class, Vehicle, which inherits from the Vehicle class in DroneKit. 我正在尝试创建一个类Vehicle,该类继承自DroneKit中的Vehicle类。 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. 此类的目的是让我重写DroneKit中存在的某些不适用于PX4的方法,并添加一些我自己的方法,同时仍可访问默认情况下的所有可用方法。
The issue is that you don't create a Vehicle object directly using Dronekit – you call the connect() function which return a Vehicle object. 问题是您没有直接使用Dronekit创建Vehicle对象,而是调用connect()函数来返回Vehicle对象。
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: 可接受的方法似乎是调用父init (),如下所示:
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, eg vehicle = Vehicle(stuff), but by vehicle = connect(stuff), which eventually returns a Vehicle object but also does a bunch of other stuff. 但是就像我说的那样,您不是直接在Dronekit中创建Vehicle对象,例如vehicle = Vehicle(stuff),而是通过vehicle = connect(stuff),这最终会返回Vehicle对象,但还会执行其他操作。
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. 然后必须使用self.vehicle.function()来访问默认的DroneKit命令和属性,这是一个很大的麻烦。
How do I make this work? 我该如何工作?
The way objects are defined has nothing to do with connect
. 定义对象的方式与connect
无关。 Calling connect
is merely some convenience function that wraps some logic around the object creation : 调用connect
只是一些便利功能,它围绕对象创建包装了一些逻辑 :
def connect(...):
handler = MAVConnection(...)
return Vehicle(handler)
with Vehicle.__init__()
being defined as 将Vehicle.__init__()
定义为
def __init__(self, handler):
super(Vehicle, self).__init__()
self._handler = handler
...
So as long as you pass on the handler in your constructor: 因此,只要您在构造函数中传递处理程序:
class MyVehicle(dronekit.Vehicle):
def __init__(self, handler):
super(MyVehicle, self).__init__(handler)
Your class will work with connect()
: 您的班级将使用connect()
:
connect(..., vehicle_class=MyVehicle)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.