简体   繁体   English

python类关键字参数

[英]python class keyword arguments

I'm writing a class for something and I keep stumbling across the same tiresome to type out construction. 我正在写一个类的东西,我一直在磕磕绊绊地想要施工。 Is there some simple way I can set up class so that all the parameters in the constructor get initialized as their own name, ie fish = 0 -> self.fish = fish ? 是否有一些简单的方法可以设置类,以便构造函数中的所有参数都被初始化为自己的名称,即fish = 0 -> self.fish = fish

class Example(object):
    def __init__(self, fish=0, birds=0, sheep=0):
        self.fish = fish
        self.birds = birds
        self.sheep = sheep

Short answer: no. 简答:不。 You are not required to initialize everything in the constructor (you could do it lazily), unless you need it immediately or expose it (meaning that you don't control access). 您不需要初始化构造函数中的所有内容(您可以懒惰地执行),除非您需要立即或暴露它(意味着您不能控制访问)。 But, since in Python you don't declare data fields, it will become difficult, much difficult, to track them all if they appear in different parts of the code. 但是,因为在Python中你没有声明数据字段,所以如果它们出现在代码的不同部分中,那么跟踪它们将变得困难,非常困难。

More comprehensive answer: you could do some magic with **kwargs (which holds a dictionary of argument name/value pairs), but that is highly discouraged, because it makes documenting the changes almost impossible and difficult for users to check if a certain argument is accepted or not. 更全面的答案:你可以用**kwargs (它包含一个参数名称/值对的字典)做一些魔术,但这是非常气馁的,因为它使记录变化几乎不可能,用户很难检查某个参数被接受与否。 Use it only for optional, internal flags. 仅将其用于可选的内部标志。 It could be useful when having 20 or more parameters to pass, but in that case I would suggest to rethink the design and cluster data. 当有20个或更多参数通过时,它可能很有用,但在这种情况下,我建议重新考虑设计和集群数据。

In case you need a simple key/value storage, consider using a builtin, such as dict . 如果您需要简单的键/值存储,请考虑使用内置命令,例如dict

You could use the inspect module: 您可以使用inspect模块:

import inspect

class Example(object):

    def __init__(self, fish=0, birds=0, sheep=0):
        frame = inspect.currentframe()
        args, _, _, values = inspect.getargvalues(frame)
        for i in args:
            setattr(self, i, values[i])

This works, but is more complicated that just setting them manually. 这可行,但只是手动设置它们更复杂。 It should be possible to hide this with a decorator: 应该可以用装饰器隐藏它:

@set_attributes
def __init__(self, fish=0, birds=0, sheep=0):
    pass

but defining set_attributes gets tricky because the decorator inserts another stack frame into the mix, and I can't quite get the details right. 但定义set_attributes变得棘手,因为装饰器将另一个堆栈帧插入到混合中,我无法完全了解详细信息。

For Python 3.7+, you can try using data classes in combination with type annotations. 对于Python 3.7+,您可以尝试将数据类与类型注释结合使用。

https://docs.python.org/3/library/dataclasses.html https://docs.python.org/3/library/dataclasses.html

Import the module and use the decorator. 导入模块并使用装饰器。 Type-annotate your variables and there's no need to define an init method, because it will automatically be created for you. 对变量进行类型注释,无需定义init方法,因为它会自动为您创建。

from dataclasses import dataclass

@dataclass
class Example:
    fish: int = 0
    birds: int = 0
    sheep: int = 0

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

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