我试图复制一个Java库的API来解决一个车辆路径问题,它突出了一些我不了解的Python类。你知道吗
车队可分为两个基本标准:第一个是您拥有的车辆类型(例如VehicleType
定义容量、运行成本等)和单独的车辆(Vehicle
具有不同的换档模式等)。你知道吗
在我的简化示例中,我想定义一个VehicleType
,然后是一个Vehicle
,它接受传递给构造函数的VehicleType
的属性。遵循Lennart here的答案,使用__getattr__
在一般情况下非常有效。但是,假设50个van中有一个司机有特殊的资格携带危险物品,所以我想在Vehicle
实例上添加一个额外的capacity属性。我尝试了以下方法:
class VehicleType(object):
def __init__(self, fixed_cost=0, cost_per_distance=0, cost_per_time=0):
self.capacities = {}
self.fixed_cost = fixed_cost
self.cost_per_distance = cost_per_distance
self.cost_per_time = cost_per_time
def add_capacity_dimension(self, dimension_id, dimension_size):
""" Define a package type and how many of them this vehicle type can carry """
self.capacities[dimension_id] = dimension_size
class Vehicle(object):
def __init__(self, vehicle_type=None, identifier=None):
self._vehicle_type = vehicle_type
self.identifier = identifier
def add_capacity_dimension(self, dimension_id, dimension_size):
self.capacities[dimension_id] = dimension_size
def __getattr__(self, name):
return getattr(self._vehicle_type, name)
if __name__ == '__main__':
van_type = VehicleType()
van_type.add_capacity_dimension("general items", 34)
special_van = Vehicle(vehicle_type=van_type)
special_van.add_capacity_dimension("hazardous chemicals", 50)
print("Capacities of special van: {}".format(special_van.capacities))
print("Capacity of van_type: {}".format(van_type.capacities)) # Why?
我不明白为什么我的方法也影响了capacities
的van_type
。Vehicle
不直接从VehicleType
继承,我在Vehicle
类中定义了add_capacity_dimension
。这也与我对the docs关于__getattr__
的理解相矛盾:
Called when an attribute lookup has not found the attribute in the usual places (i.e. it is not an instance attribute nor is it found in the class tree for self). name is the attribute name.
有人能解释一下为什么这里的实例van_type
也会受到影响吗?你知道吗
Vehicle
实例没有“capacities”属性。你知道吗在
special_van
(在Vehicle.add_capacity_dimension
实现中)上的self.capacities
属性查找不是在Vehicle
上解析的,而是通过自定义的__getattr__
在VehicleType
上解析的。你知道吗因此,
special_van.capacities
和van_type.capacities
是同一个dict相关问题 更多 >
编程相关推荐