[英]Is there a cleaner way to pass kwargs from class to a function
我剛剛開始在 python 類中使用 kwargs,我相信這是一個微不足道的問題,但我無法在網上找到足夠的答案。
我有一個 class,它的配置值在許多函數中使用,但是有些調用必須否決該值
這是我在冗長上下文中的問題的簡化版本:
我的要求是:
test().func() -> "Verbose = True"
test(verbose=False).func() -> "Verbose = False"
test().func(verbose=False) -> "Verbose = False"
test.func() -> "Verbose = True"
我的解決方案:
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}")
我的問題:這似乎不是解決問題的正確方法。 這似乎是一種復雜的處理方式,感覺就像我缺少一個內置或標准的解決方案。 一個更大的問題是我不喜歡我必須為每個變量以及我想這樣處理的每個 function 做這樣的一行。
謝謝
您可以使用帶有默認值的get()
方法。
def funct(self, **kwargs):
verbose = kwargs.get('verbose', self.verbose)
print(f"Verbose = {verbose}")
順便說一句, self
不需要默認值,因為這個參數總是自動傳遞給方法。
我相信這就是您正在尋找的:
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.