简体   繁体   English

有没有更干净的方法将 kwargs 从 class 传递到 function

[英]Is there a cleaner way to pass kwargs from class to a function

I'm just getting started with kwargs in python classes, and I'm confident this is a trivial question, but I cannot find a sufficient answer online.我刚刚开始在 python 类中使用 kwargs,我相信这是一个微不足道的问题,但我无法在网上找到足够的答案。

I have a class that with config values that are used in many functions, however there are some calls where the value has to be overruled我有一个 class,它的配置值在许多函数中使用,但是有些调用必须否决该值

Here is a simplified version of my problem with the context of verbosity:这是我在冗长上下文中的问题的简化版本:

My requirements are:我的要求是:

  1. verbose becomes the config value if not declared otherwise如果未另行声明,verbose 将成为配置值
test().func() -> "Verbose = True"
  1. verbose becomes the kwarg passed to the class upon init. verbose 成为在初始化时传递给 class 的 kwarg。
test(verbose=False).func() -> "Verbose = False"
  1. verbose becomes the kwarg passed to the function upon func call. verbose 成为在 func 调用时传递给 function 的 kwarg。
test().func(verbose=False) -> "Verbose = False"
  1. (optionally but not necessary at the sacrifice of even an extra line of complexity): verbose becomes config even without init (可选但不是必要的,甚至会牺牲额外的复杂性):即使没有 init,verbose 也会变成配置
test.func() -> "Verbose = True"

My Solution:我的解决方案:

class test():

    CONFIG = {"verbose":True}

    def __init__(self,**kwargs):
        self.__dict__.update(self.CONFIG)
        self.__dict__.update(**kwargs)
    
        
    def func(self=None,**kwargs):
        verbose = kwargs['verbose'] if 'verbose' in kwargs else self.verbose
        print(f"Verbose = {verbose}")

My Problem: This doesn't seem like the right way to tackle the problem.我的问题:这似乎不是解决问题的正确方法。 This seems like a convoluted way to handle this, and it feels like there is a built-in or standard solution I'm missing.这似乎是一种复杂的处理方式,感觉就像我缺少一个内置或标准的解决方案。 An even bigger issue is that I don't like that I have to make a line like this for every variable and in every function that I want to treat like this.一个更大的问题是我不喜欢我必须为每个变量以及我想这样处理的每个 function 做这样的一行。

Thanks谢谢

You can use the get() method with a default.您可以使用带有默认值的get()方法。

def funct(self, **kwargs):
    verbose = kwargs.get('verbose', self.verbose)
    print(f"Verbose = {verbose}")

BTW, there's no need for a default for self , since this argument is always passed automatically to methods.顺便说一句, self不需要默认值,因为这个参数总是自动传递给方法。

I believe this is what you're looking for:我相信这就是您正在寻找的:

class test():
    # A class variable will act as a default value for objects.
    verbose = True

    def __init__(self,**kwargs):
        # It's better to use setattr. Modifying __dict__ might bypass some
        # important automated stuff.
        for k, v in kwargs.items():
            setattr(self, k, v)
    
    # self must not be None. 'None.verbose' is an error.
    def func(self, **kwargs):
        # Use the get method when the value might not be in the dict.
        verbose = kwargs.get('verbose', self.verbose)
        print(f"Verbose = {verbose}")

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

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