Python 的 带默认值获取属性

等级 4177 次按键

这使用带默认值的getattr()安全访问对象属性。

Python 代码

# 有两个类属性的类;没有定义host
1class Config:
2 debug = True
3 port = 8080
4
# 实例可以读取类属性
5config = Config()
# 以字符串保存、运行时才确定的属性名
6attrs = ["debug", "port", "host"]
7for attr in attrs:
# 按名称获取属性;不存在时返回"Not set"而不是抛出AttributeError
8 value = getattr(config, attr, "Not set")
# 打印debug: True、port: 8080、host: Not set
9 print(f"{attr}: {value}")

运行结果

debug: True
port: 8080
host: Not set
用这段代码练习打字

可以用这段代码练习打字。成绩不会计入排行榜。

这段代码中的符号

这段 Python 代码中需要输入的符号及其出现次数。

  • "× 10
  • =× 5
  • ,× 4
  • :× 3
  • (× 3
  • )× 3
  • {× 2
  • }× 2
  • [× 1
  • ]× 1

Python 等级 4 的更多代码示例

← 返回 Python 打字练习