繁体   English   中英

python 使用 class 参数作为自己

[英]python using class param as self

我是 python 的新手,我想知道是否可以使用一种方法来操作所有 class 属性,例如:

class Test:
    def __init__(self, dict1 = {"test": 0}, dict2 = {"another_test": 0}):
        self.dict1= dict1
        self.dict2 = dict2

    def vary_attr(self, attr, key, value):
        self.attr[key] += value

x = Test()
x.vary_attr('dict1', 'test', 3)
x.vary_attr('dict2', 'another_test', 6)

print(x.dict1)

# Wishful output:
# {'test': 3}
# {'another_test': 6}

显然,这不起作用,但有可能使它起作用吗? 拥有一种方法并通过该方法同时使用属性 dict1 和 dict2 进行操作?!

实际上,您的用例是首先获取字典属性,然后进行必要的更新。 您可以使用getattr获取属性,然后执行必要的操作。

class Test:
    def __init__(self, dict1 = {"test": 0}, dict2 = {"another_test": 0}):
        self.dict1= dict1
        self.dict2 = dict2

    def vary_attr(self, attr, key, value):
        # get class attribute by attribute name attr
        _atr = getattr(self, attr)
        _atr.update({key: _atr.get(key, 0)+value})

x = Test()
x.vary_attr('dict1', 'test', 3)
x.vary_attr('dict2', 'another_test', 6)
# x.dict1, x.dict2
# ({'test': 6}, {'another_test': 6})

请注意,您的用例不需要动态设置属性,因为dict.update是可变的 function,但对于其他用例,您可以使用setattr并将selfattrvalue作为参数传递。

暂无
暂无

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

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