python 中的默认值
Python 2024/6/28 9:17:19 点击:不统计
http://%77%77%77%2E%66网站制作%6F学习网%72%61%73%70%2E%63%6E
# python中对象属性,dict默认值,获取不存在的key 的属性时,如何返回默认值
# 第一种在字典中,如果 key 不存在,则返回一个默认值
d = {"site":"www.forasp.cn"}
print(d.get("url", "http://www.forasp.cn"))
# 字典中的默认值, 如果存在,则直接返回url 值,如果不存在,则返回默认值
url = d.setdefault("url", "http://www.forasp.cn")
site = d.setdefault("site", "newsite")
print(url, site)
"""result:
http://www.forasp.cn
http://www.forasp.cn www.forasp.cn
"""
# 字典中的默认值,可以是一个函数返回的对象结构,可以是list,或者自定义的类对象等,注意必须时函数返回
# 可以指定默认的值为一个类型
from collections import defaultdict
e = defaultdict(int)
e['a'] +=1
print(e) #
# 第二种 类对象属性等默认值,是通过魔术方法来实现的
class A:
def __init__(self):
self._attributes = {}
def __getattr__(self, name):
# 这里是找到对应的属性,如果找不到,则返回 None
if name in self._attributes:
return self._attributes[name]
else:
return None
def __setattr__(self, name, value):
# Avoid recursion by directly setting attributes in the instance dictionary
if name == '_attributes':
super().__setattr__(name, value)
else:
print(f"Setting attribute '{name}' to '{value}'")
self._attributes[name] = value
pass
a = A()
print(a.a)
# 第三种,获取系统变量的默认值
import os
os_v = os.getenv("site_name", "default_value")
print(os_v)
·上一篇:python设置读取对象属性 >> ·下一篇:python 异常自检查程序 >>