gpt4 book ai didi

python - 将对象类型作为参数传递

转载 作者:行者123 更新时间:2023-11-30 21:54:02 25 4
gpt4 key购买 nike

我有一些代码希望以比我的直觉想要的更优雅的方式实现。我将尽力描述我正在尝试的内容。

class Fruit():
pass

class Apple(Fruit):
pass

class Orange(Fruit):
pass

def create_fruit(fruit_type):
test = ???? # code here to create instance of fruit of desired type called test

好的,希望这段代码能有意义。我在模块中有一个函数,它需要一堆参数来创建类的实例。理想情况下,我希望传递一个参数来说明要创建的类的类型(但它们都是同一父类(super class)的实例或子类)。每个子类的参数将是相同的(截至目前)。

我可能可以很容易地用 if 语句做一些事情并组合在一起(例如,iffruit_type==1test=Apple(),i f Fruit_type == 2test=Orange() 等...),但在尝试提高 Python 程序员水平时,我想知道是否有更好的方法来做到这一点。我已经简要阅读了装饰器和函数式编程(尽管它对我来说仍然相当抽象,并且需要更多时间来理解),所以也许这也是同样的脉络?

最佳答案

如果你只用类名调用create_fruit,然后实例化参数会怎么样:

def create_fruit(fruit_type):
test = fruit_type()

create_fruit(Apple)

(编辑以将赋值添加到“test”变量)或者你也可以做类似的事情,这实际上允许你在 create_fruit 之外对你创建的水果做一些事情:

def create_fruit(fruit_type):
return fruit_type()

test = create_fruit(Apple)
test.bite()

关于python - 将对象类型作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59430736/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com