gpt4 book ai didi

python - (Python) 可以解释一下这个函数在做什么吗(使用对象属性)

转载 作者:太空宇宙 更新时间:2023-11-03 13:04:28 25 4
gpt4 key购买 nike

我正在对一个旧的 Python 脚本进行代码维护。我遇到了一段代码,这让我很困惑。在代码的前面(未显示在下面的代码片段中),定义了具有最少属性的类。在代码的后面,对类中不存在的字段进行了分配。例如

tempvar = MyClassObject()
tempvar.this_field_was_not_defined_in_the_class = 42

稍后在脚本中,通过调用将变量 tempvar 写入 CSV 文件:

write_csv('test.csv', tempvar, ('declared_field1', 'declared_field2',
('declared_field3', 'New Label'),
'this_field_was_not_defined_in_the_class') )

这是将对象写入文件的(令我感到困惑的)函数:

def write_csv(filename, objects, fields, add_weightings=True):
# The items in fields can either be a tuple of the attribute name and a label for that
# attribute, or just an attribute name. In the later case replace it with a tuple with an
# automatically generated label.
fields = list(fields)
for i in xrange(len(fields)):
if isinstance(fields[i], tuple):
continue
else:
fields[i] = (fields[i], fields[i].replace('_', ' '))

with open(filename, 'wb') as f:
f.write(codecs.BOM_UTF8)
c = csv.DictWriter(f, [i[0] for i in fields])
c.writerow(dict(fields))
c.writerows(
[utf8ify(add_weighting(i.__dict__) if add_weightings else i.__dict__) for i in objects])

谁能解释一下这是怎么回事?顺便说一句,utf8ifyadd_weighting 是脚本中定义的全局函数。

最佳答案

对象没有“不存在”的属性。没有声明。

属性仅分配给 __init__ 或任何引用该对象的代码中的对象。那只是标准的 Python。

class Whatever( object ):
pass

w = Whatever()
w.new_attribute= "some value"

完全正常。 new_attribute 属性并非“不存在”,因为它不需要任何类型的声明。

当你做的时候

>>> w.__dict__

在交互式提示中,您会看到属性所在的位置。

关于python - (Python) 可以解释一下这个函数在做什么吗(使用对象属性),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8851780/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com