I'm new in python and try to solve this problme.I apologize if I am not realy good in English. for thid issue I shuldn't change the argument of methods except dunder call.I only brought the part of the code that I had a problem with. I try to use attribute of Passenger class(self.load_weight) in Trip class. but I get error (TypeError: unsupported operand type(s) for -=: 'int' and 'Trip').how can I print the answer without any error?
class Train:
def __init__(self, weight_capacity):
self.weight_capacity = weight_capacity
class Trip:
def __init__(self, train):
self.train = self.train_validation(train))
def train_validation(self, train):
self.train = train
return self.train
def __call__(self):
self.trip = Passenger(self)
self.train.weight_capacity -= self.trip.load_weight
return self.train.weight_capacity
class Passenger:
def __init__(self , load_weight):
self.load_weight = load_weight
def attend_trip(self, trip):
self.trip = trip
train = Train(34286)
trip = Trip(train)
passenger1 = Passenger(616)
print(trip())
CodePudding user response:
The problem with your code is that in the line self.trip = Passenger(self)
use pass the Train object as an argument. Maybe it's an mistype, because in the Passenger class you named the variable load_weight
. So I am assuming you should pass some kind of number instead of class object.
CodePudding user response:
The reason why your code is not working as expected is because inside the call dunder method of Trip class, you are instancing a new Passenger class instance, instead of using the passenger class instanced below; plus the fact that you are creating the passenger instance itself after the Trip instance (the last 3 lines),
I've done a small refactor of you code, with the suggested modifications:
class Train:
def __init__(self, weight_capacity):
self.weight_capacity = weight_capacity
class Trip:
def __init__(self, train):
self.train = self.train_validation(train)
def train_validation(self, train):
self.train = train
return self.train
def __call__(self, passenger):
self.trip = passenger
self.train.weight_capacity -= self.trip.load_weight
return self.train.weight_capacity
class Passenger:
def __init__(self, load_weight):
self.load_weight = load_weight
def attend_trip(self, trip):
self.trip = trip
train = Train(34286)
passenger1 = Passenger(616)
trip = Trip(train)
print(trip(passenger1))