Python 如何在初始化期间将多个参数传递给类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32005839/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 10:51:32  来源:igfitidea点击:

how to pass multiple parameters to class during initialization

python

提问by Abhishek Dave

I have a requirement where things are all on scripts. No config file. Now i want to initialize a class using ~30 odd parameters. All objects will have different parameter values.

我有一个要求,一切都在脚本上。没有配置文件。现在我想使用 ~30 个奇数参数初始化一个类。所有对象将具有不同的参数值。

Can't figure out the best way to do it.

想不出最好的办法。

class doWorkWithItems():
    def __init__(self, dueX,dueY,dueZ,..):
        self.dueX = dueX
        ....
    def func1(self):
        work with above variables till object destroy.
worker1=doWorkWithItems(divX,divY,divZ,....)

回答by luoluo

class doWorkWithItems(object):
    def __init__(self, dueX,dueY,dueZ,..):
        self.dueX = dueX
        ....
    def func1(self):
        work with above variables till object destroy.
worker1=doWorkWithItems(divX,divY,divZ,....)

回答by rolika

class doWorkWithItems:
    def __init__(self, dueX,dueY,dueZ,..):
        self.dueX = dueX
        ....
    def func1(self):
        work with above variables till object destroy.

 worker1=doWorkWithItems(divX,divY,divZ,....)

If you put something in parentheses behind the class name, it's inheritance. The arguments should appear in __init__()as you wrote.

如果你把一些东西放在类名后面的括号里,那就是继承。参数应该在__init__()你写的时候出现。

回答by Vivek Anand

Initialization of an object in python is done using the constructor method which is: init method so whatever arguments you are passing to make an object out of that class is going to init method. So, only that method should have those parameters. Those should not be present along with the class name.
Python uses that for inheritance purpose. Read thisfor more on inheritance.
For cleaner code i would suggest using *args and **kwargs

python 中对象的初始化是使用构造函数方法完成的,该方法是: init 方法,因此您传递的用于从该类中创建对象的任何参数都将传递给 init 方法。所以,只有那个方法应该有这些参数。这些不应与类名一起出现。
Python 将其用于继承目的。阅读本文以了解有关继承的更多信息。
对于更干净的代码,我建议使用*args 和 **kwargs

回答by SuperBiasedMan

First, you've misunderstood the class declaration in Python.

首先,您误解了 Python 中的类声明。

This line:

这一行:

class doWorkWithItems(dueX,dueY,dueZ,...):

should have the class/es to inherit from in the brackets. ie. class doWorkWithItems(object)or class doWorkWithItems(str). So your new class is trying to inherit from all those objects you've passed it.

应该在括号中包含要继承的类。IE。class doWorkWithItems(object)class doWorkWithItems(str)。所以你的新类试图从你传递给它的所有对象中继承。

When you want to pass initialisation parameters you just need to pass them within the __init__function as you were doing.

当你想传递初始化参数时,你只需要__init__像你所做的那样在函数内传递它们。

class doWorkWithItems(object):
    def __init__(self, dueX,dueY,dueZ,..):

As for the best way to have a long list of arguments, Python has an operator for that, it's *. It unpacks a collection of items. It's commonly used with the name argsand will allow for any amount of parameters to be passed in.

至于获得一长串参数的最佳方法,Python 有一个运算符,它是*. 它打开一组物品的包装。它通常与名称一起使用,args并允许传入任意数量的参数。

    def __init__(self, *args):
        self.args = args

It might be a good idea though, to store these values as a dictionary if they're for different uses, as that's easier to access than a plain list. You can turn the *argsinto a dictionary pretty easily if you pass every argument as a 2 element tuple like this:

不过,如果这些值用于不同用途,将它们存储为字典可能是个好主意,因为这比普通列表更容易访问。*args如果您将每个参数作为 2 元素元组传递,则可以很容易地将其转换为字典:

    def __init__(self, *args):
        try:
             self.args = dict(args)
        except TypeError:
             #What to do if invalid parameters are passed

    ...

    obj = doWorkWithItems( ("Name", "John"), ("Age", 45), ("Occupation", "Professional Example"), )
    obj.args
    >>> {'Age': 45, 'Name': 'John', 'Occupation': 'Professional Example'}

But there is a better approach you could do if you pass parameters in a dictionary:

但是,如果您在字典中传递参数,则可以采用更好的方法:

    def __init__(self, params):
        self.name = params.get('name')
        self.age = params.get('age')
        self.occupation = params.get('occupation')

The .getmethod will return a key from a dictionary, but if no key is found it will return None. This way all your class's variables can be created even if they're unspecified in parameters, they'll just be set to None. You don't need to access all the attributes through a dictionary, and it handles errors as long as you are passing a dictionary.

.get方法将从字典中返回一个键,但如果没有找到键,它将返回None. 这样,即使未在参数中指定所有类的变量,也可以创建它们,它们只会被设置为None. 您不需要通过字典访问所有属性,只要您传递字典,它就会处理错误。

回答by mfathi

If you want use a function that gets two parameters in a class. You can use my simple code:

如果要使用在类中获取两个参数的函数。您可以使用我的简单代码:

class my_class:
  variable = "0"
  def function(self):
      print("sample function in class!!")
  a = 0
  b = 0
  def sum(self, a , b):
      print(a + b)

sample_object = my_class()

sample_object.sum(25,60)