Python 的 带默认值获取属性
等级 4177 次按键
这使用带默认值的getattr()安全访问对象属性。
Python 代码
# 有两个类属性的类;没有定义host1class Config:2 debug = True3 port = 80804 # 实例可以读取类属性5config = Config()# 以字符串保存、运行时才确定的属性名6attrs = ["debug", "port", "host"]7for attr in attrs: # 按名称获取属性;不存在时返回"Not set"而不是抛出AttributeError8 value = getattr(config, attr, "Not set") # 打印debug: True、port: 8080、host: Not set9 print(f"{attr}: {value}")运行结果
debug: True port: 8080 host: Not set
可以用这段代码练习打字。成绩不会计入排行榜。
这段代码中的符号
这段 Python 代码中需要输入的符号及其出现次数。
"× 10=× 5,× 4:× 3(× 3)× 3{× 2}× 2[× 1]× 1