简体   繁体   English

在 Python 中将 arguments 传递给 function

[英]Passing arguments to function in Python

In a simplified example, say I have在一个简化的例子中,假设我有

class Car:
  def __init__(self, operation):
    self.operation = operation

def change_wheels(car, wheel_type):
  ...
def repair_brakes(car, brake_pads, brake_fluid):
  ...

car_list = [Car(change_wheels), Car(repair_brakes)]

def service_car(car, wheel_type, brake_pads, brake_fluid):
  car.operation(???)

How do I pass the required arguments to the operation function?如何将所需的 arguments 传递给operation function?

You could give Car parameters, like wheel type, brake type, etc. And pass the car object to the functions, then retrieve the car's parameters.您可以提供Car参数,如车轮类型、刹车类型等。并将汽车 object 传递给函数,然后检索汽车的参数。 These attributes is corresponding to each car, because they have different brake types etc... And passing these objects to the functions makes easier to get the needed parameters later.这些属性是对应每辆车的,因为它们有不同的刹车类型等……将这些对象传递给函数可以让以后更容易获得所需的参数。

class Car:
    def __init__(self, wheel, brakes, operation):
        self.wheel     = wheel
        self.brakes    = brakes
        self.operation = operation

def change_wheels(car):
    print('Wheel', car.wheels)

def repair_brakes(car):
    print('Brakes', car.brakes)

car_list = [Car('Wheel type', 'Brake type', change_wheels), Car('Wheel type', 'Brake type', repair_brakes)]

for car in car_list:
    car.operation(car)

Not all parameters were implemented, this is just an example!并非所有参数都已实现,这只是一个示例!

Not sure what you want, but how about:不确定你想要什么,但是怎么样:

class Car:
  def __init__(self, operation):
    self.op = operation
  
  def __call__(self, *args, **kwargs):
    try: self.op(self, *args, **kwargs)
    except TypeError: print('Unsupported operation.')

def change_wheels(car, wheel_type):
  print('change_wheels()', wheel_type)

def repair_brakes(car, brake_pads, brake_fluid):
  print('repair_brakes()', brake_pads, brake_fluid)

car_list = [Car(change_wheels), Car(repair_brakes)]

def service_car(car, wheel_type, brake_pads, brake_fluid):
  #car.operation(???)
  car(wheel_type)
  car(brake_pads, brake_fluid)

for car in car_list: service_car(car, 'wt', 'bp', 'bf')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM