Pythonic:在类的self .__ init__函数中使用__dict__ [英] Pythonic: use of __dict__ in the function self.__init__ of a class

查看:99
本文介绍了Pythonic:在类的self .__ init__函数中使用__dict__的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

虽然使用 spyder IDE编码一个新类,并使用 pylint 检查最终结果,但我遇到了错误消息(但是代码按预期工作没有错误)。

While coding a new class with the spyder IDE, and using pylint to check the final result, I've ran into error messages (but the code work as expected without error).

上下文:在构造函数中,我想创建新成员(很多)。通常,这些数目很少,因此我使用以下编码:

Context: in the constructor function, I want to create new members (quite a lot). Usually, these are few enough so I use this coding:

class MyClass():
    def __init__(self):
        self.a = ...
        self.b = ...

但是对于许多成员(假设10个成员),并且所有成员都设置为相同的初始值(假设它们都是dict()),我很想这样做:

But in a case of many members (let's say 10), with all set to the same initial value (let's say they are all dict()), I was tempted to do that:

class MyClass():
    def __init__(self):
        _vars = ["a", "b", "c", ...]
        for _var in _vars:
            self.__dict__[_var] = dict()

在该类中,我还使用以下方式指代成员:

Further in the class, I was refering to a member using:

class MyClass():
    def my_method(self):
        print self.c

错误 pylint (在 spyder 中):

在此文件上使用pylint时,错误消息:

When using pylint on this file, I've got an error message saying:


MyClass.my_method: MyClass的实例没有c成员。

MyClass.my_method: instance of 'MyClass' has no 'c'member.

但是,代码运行得很好,没有错误,即。我可以毫无问题地访问成员'c'。

However, the code runs just fine, without error, ie. I may access the member 'c' without any problem.

问题:这是正确的编码,还是应该避免这种方法

Question: is this a proper coding, or should I avoid such a method to initialize members?

推荐答案

是的,直接更新实例字典是合理的。另外,您可以使用 setattr 更新变量。我已经看到了生产代码中使用的两种方法。

Yes, it is reasonable to update the instance dictionary directly. Alternatively, you can use setattr to update the variables. I've seen both approaches used in production code.

使用 setattr 无需直接触摸实例字典:

With setattr there is no need to touch the instance dictionary directly:

class MyClass():
    def __init__(self):
        for var in 'a', 'b', 'c':
            setattr(self, var, dict())

但是,如果直接更新实例字典,则需要考虑一些可能的改进。例如,使用 vars() 代替 __ dict __ 看起来更好看。另外,您可以使用 dict.update 具有关键字参数的方法:

But if you update the instance dictionary directly, there are couple possible improvements to consider. For example, using vars() instead of __dict__ is a bit nicer looking. Also, you can use the dict.update method with keyword arguments:

class MyClass():
    def __init__(self):
        vars(self).update(a=dict(), b=dict(), c=dict())

这篇关于Pythonic:在类的self .__ init__函数中使用__dict__的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆