在Python中的类变量的条件赋值

huangapple go评论68阅读模式
英文:

Conditional assignment of class variable in Python

问题

我可以帮你翻译以下代码部分:

# 使用默认值或者从kwargs中设置属性
default = 1

class foo():
    def __init__(self, **kwargs):
        self.X = kwargs['X'] if 'X' in kwargs else default
        self.Y = kwargs['Y'] if 'Y' in kwargs else default

F = foo()
f = foo(X=2, Y=3)

这段代码会在foo类的初始化方法中根据传入的关键字参数kwargs来设置属性XY的值,如果kwargs中没有对应的键值,将使用默认值default。这种方法可以实现你想要的条件性设置属性的效果。

英文:

How can I conditionally set an attribute in the __init__ of a class, from a **kwargs parameter?

I know that I can do:

default = 1

class foo():
    def __init__(self, X=None, Y=None):
        self.X = X if X else default  
        self.Y = Y if Y else default

F = foo()
f = foo(X=2, Y=3)

but I want to make this work with a variable-keyword parameter (**kwargs), in order to understand them properly.

These attempts did not work:

default = 1

class foo():
    def __init__(self, **kwargs):
        self.X = default or kwargs['X'] 
        self.Y = default or kwargs['Y']

F = foo()
f = foo(X=2, Y=3)

This way, only the default value is used even if other values are provided. If the order is switched (kwargs['X'] or default etc.), the code raises a KeyError if the keyword arguments are not provided.

default = 1

class foo():
    def __init__(self, **kwargs):
        self.X = value if kwargs["X"] is None else kwargs["X"]
        self.Y = value if kwargs["Y"] is None else kwargs["Y"]

F = foo()
f = foo(X=2, Y=3)

This still raises a KeyError for missing keyword arguments.

答案1

得分: 0

类 foo():
    def __init__(self, **kwargs):
        self.X = kwargs.get('X', value) # get() 接受键名,以及默认值选项
        self.Y = kwargs.get('Y', value)


# 或者使用带有默认值的普通参数
类 foo():
    # 将字典改为任何类型
    def __init__(self, x = None, y = None):
        self.X = x or value
        self.Y = y or value 


# 或者更好地使用带有默认值的关键字参数,如果只有 x 和 y

类 foo():
    # 将字典改为任何类型
    def __init__(self, x: dict = None, y: dict = None):
        self.X = x or value
        self.Y = y or value 

你还需要知道什么时候应该使用 **kwargs。

有两种常见情况:

第一种:你正在包装另一个接受许多关键字参数的函数,但你只是要将它们传递下去:

def my_wrapper(a, b, **kwargs):
    先做些事情(a, b)
    真正的函数(**kwargs)

第二种:你愿意接受任何关键字参数,例如在对象上设置属性:

类 OpenEndedObject:
    def __init__(self, **kwargs):
        for k, v in kwargs.items():
            setattr(self, k, v)

foo = OpenEndedObject(a=1, foo='bar')
assert foo.a == 1
assert foo.foo == 'bar'

如果需要了解更多,请阅读以下内容:

为什么在Python中使用kwargs?有了实际应用场景,有何优势?

英文:
class foo():
    def __init__(self, **kwargs):
        self.X =  kwargs.get('X', value) # get() take key_name, default value this opetions 
        self.Y = kwargs.get('Y', value)


# or use normal params with default value 
class foo():
    # change dict to  any type
    def __init__(self, x = None, y = None):
        self.X =  x or value
        self.Y = y or value 


# or better use Keyword Argument with default value if you have x y only 

class foo():
    # change dict to  any type
    def __init__(self, x: dict = None, y: dict = None):
        self.X =  x or value
        self.Y = y or value 

you need also know when should use **kwargs

There are two common cases:

First: You are wrapping another function which takes a number of keyword argument, but you are just going to pass them along:

def my_wrapper(a, b, **kwargs):
    do_something_first(a, b)
    the_real_function(**kwargs)

Second: You are willing to accept any keyword argument, for example, to set attributes on an object:

class OpenEndedObject:
    def __init__(self, **kwargs):
        for k, v in kwargs.items():
            setattr(self, k, v)

foo = OpenEndedObject(a=1, foo='bar')
assert foo.a == 1
assert foo.foo == 'bar'

read this if you need know more

https://stackoverflow.com/questions/1415812/why-use-kwargs-in-python-what-are-some-real-world-advantages-over-using-named

huangapple
  • 本文由 发表于 2023年7月10日 23:52:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/76655404.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定