python - 如何自动为python中的类添加属性?

标签 python pycharm

我有一个类,在实例化 (init) 时提供了很多属性。

看起来像这样,但还有大约 30 个属性:

class SomeObject:
    def __init__(self,
                 first,
                 second):
        self.first = first
        self.second = second

工作正常,但会变得很长且重复且难以更新。

在我使用一个更小的类之前:

class SomeObject:
    def __init__(self, **attr):
        self.__dict__.update(attr)

工作正常,更容易,但很难跟踪。使用 IDE(我使用 PyCharm)时,我在编写对象时没有提示,自动完成提示通常不起作用。

我会寻找这两个类的一些组合,例如:

class SomeObject:
    def __init__(self,
                 first,
                 second):
    self.__dict__.update(???)  # I would like to do it in a single line, so I dont have to write a new attr two (three...) times.

有人知道这是否可能/如何实现?非常感谢

python 3.4 + PyCharm 2016.1 社区版

...编辑/附加...

问题似乎主要是为了“保留”IDE 中的代码检查,以便自动完成等在对象上仍然可用。

最佳答案

您可以简单地使用 locals 内置的局部变量字典,然后删除 self 并更新:

class test:
    def __init__(self,
                 a,b,c,d,e,f,g,h,i,j,k,l,m,
                 n,o,p,q,r,s,t,u,v,w,x,y,z):
        args = locals()
        del args["self"]
        if "args" in args:
            del args["args"]
        self.__dict__.update(args)

args = list(range(26))

x = test(*args)

from string import ascii_lowercase as letters
assert args == [getattr(x,c) for c in letters]
print("worked")

虽然如果你真的想让你的 IDE 高兴它需要看到显式的属性分配,所以你可以改为编写代码来编写代码:

def write_init_code(func):
    self,*args = func.__code__.co_varnames
    return "\n".join(["{0}.{1} = {1}".format(self,a)
                      for a in args])

class test:
    def __init__(self,a,b,c,d,e,f,*v,**kw):
        pass #just a moment...


print(write_init_code(test.__init__))

然后只需将 write_init_code 的结果复制粘贴并缩进到实际函数中即可。

关于python - 如何自动为python中的类添加属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36325573/

相关文章:

python - 使用 if 条件列表理解以获取特定类型的文件列表

Python 2.7 编码和 feedparser

c# - 文本哈希技巧在 Python 和 C# 中产生不同的结果

python - 防止 PyCharm 打开 stub 文件 (*.pyi) 而不是源文件 (*.py)

postgresql - PyCharm PostgreSQL 方言检测

Python 点符号和日期时间对象

python - Pydev 找不到 matplotlib 模块

python - Python 如何知道要使用哪种数字类型来将任意两个数字相乘?

python - 检测 PyCharm/Python 中所有缺失的导入

python - 将 coverage.py 中的 .coverage 文件加载到 IntelliJ IDEA/PyCharm 的覆盖 View 中