I am trying to practice using the visitor design pattern, but I keep getting an error:
CarVistor.visit() takes 1 positional argument but 2 were given
I am not sure why I am getting this error?
class Vehicle:
def accept(self, VehicleVistor):
pass
class Car(Vehicle):
def accept(self, vistor):
vistor.visit(self)
class Motorcycle(Vehicle):
def accept(self, vistor):
vistor.visit(self)
class Vistor:
def visit(self):
pass
class CarVistor(Vistor):
def visit(self):
print("printing from car visitor")
class MotorcycleVistor(Vistor):
def visit(self):
print("printing from motorcycle visitor")
vehicle1 = Car()
vehicle2 = Motorcycle()
vistor1 = CarVistor()
vistor2 = MotorcycleVistor()
vehicle1.accept(vistor1)
vehicle2.accept(vistor2)
>Solution :
The self argument (the first one) is automatically passed once you call a method on an object.
You should remove the self from the arguments list:
class Vehicle:
def accept(self, VehicleVistor):
pass
class Car(Vehicle):
def accept(self, vistor):
vistor.visit()
class Motorcycle(Vehicle):
def accept(self, vistor):
vistor.visit()
class Vistor:
def visit(self):
pass
class CarVistor(Vistor):
def visit(self):
print("printing from car visitor")
class MotorcycleVistor(Vistor):
def visit(self):
print("printing from motorcycle visitor")
vehicle1 = Car()
vehicle2 = Motorcycle()
vistor1 = CarVistor()
vistor2 = MotorcycleVistor()
vehicle1.accept(vistor1)
vehicle2.accept(vistor2)
You can read here more about self.
self is the first argument of every method in Python.
When Python calls a method in your class, it will pass in the actual instance of that class that you’re working with as the first argument.
The self variable points to the instance of the class that you’re working with.
From Python’s self
There are some cases that you might want to pass self as an argument to a method/function because self is just a pointer to the instance of the class.
For example if you want the visit method to have pointers of 2 objects (the one on which you called visit and another one), you need to add another argument to the args list:
class Vehicle:
def accept(self, VehicleVistor):
pass
class Car(Vehicle):
def accept(self, vistor):
vistor.visit(self)
class Motorcycle(Vehicle):
def accept(self, vistor):
vistor.visit(self)
class Vistor:
def visit(self):
pass
class CarVistor(Vistor):
def visit(self, visitor):
print("printing from car visitor")
class MotorcycleVistor(Vistor):
def visit(self, visitor):
print("printing from motorcycle visitor")
vehicle1 = Car()
vehicle2 = Motorcycle()
vistor1 = CarVistor()
vistor2 = MotorcycleVistor()
vehicle1.accept(vistor1)
vehicle2.accept(vistor2)