类作为函数的输入
我有一个包含三个不同类的文件 different_classes 。它是这样的:
class first(object):
def __init__(x, y, z):
body of the first class
class second(first):
def __init__(x, y, z, a=2, b=3):
body of the second class
class third(object):
def __init__(x, y, z):
body of the third class
现在我有另一个文件,例如 main.py
,我希望能够在其中传递需要调用的类的名称。例如,现在我这样做:
import different_classes
def create_blah():
instance = different_classes.first()
rest of the function body
当我想使用 different_classes 中的第一个类时。如果我想使用类
second
,我会使用 different_classes.second()。
我可以在 create_blah
函数中输入类名作为参数吗?比如:
def create_blah(class_type = "first", x=x1, y=y1, z=z1):
instance = different_classes.class_type(x, y, z)
我知道这可能无效......但想知道是否可以做类似的事情。谢谢!
I have a file different_classes
that contains three different classes. It is something like:
class first(object):
def __init__(x, y, z):
body of the first class
class second(first):
def __init__(x, y, z, a=2, b=3):
body of the second class
class third(object):
def __init__(x, y, z):
body of the third class
Now I have another file, say main.py
where I want to be able to pass on the name of the class that needs to be called. For example, right now I do:
import different_classes
def create_blah():
instance = different_classes.first()
rest of the function body
when I want to use the first class in different_classes
. If I want to use class second
, I use different_classes.second().
Can I input the class name as an argument in the create_blah
function. Something like:
def create_blah(class_type = "first", x=x1, y=y1, z=z1):
instance = different_classes.class_type(x, y, z)
I know this may not be valid...but want to know if something similar can be done. Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
与其传递类的名称,为什么不只传递类本身:
请记住,类只是一个对象,就像 Python 中的其他任何东西一样:您可以将它们分配给变量并将它们作为参数传递。
如果您确实需要使用该名称,例如因为您正在从配置文件中读取它,则使用 getattr() 来检索实际的类:
Rather than passing the name of the class, why not just pass the class itself:
Remember that a class is just an object like anything else in Python: you can assign them to variables and pass them around as arguments.
If you really do need to use the name, e.g. because you are reading it from a configuration file, then use
getattr()
to retrieve the actual class:您还可以传递类对象:
class_ = different_classes.first
。You could also pass around the class object:
class_ = different_classes.first
.有点像。有一些更奇特的方法,但我推荐这个。
Sort of. Thare are fancier ways, but I suggest this one.