[Python]Understand attribute in Python

本文通过一个简单的Python代码示例展示了如何区分类的属性和项。定义了一个名为MyClass的类,并通过__getitem__方法实现了对类实例的字典式访问。通过setattr设置了类实例的属性,展示了属性和项的不同调用方式。

This recipe is a small code snippet of showing how to distinguish attribute and item in Python language.


class MyClass(object):

	def __getitem__(self, name):
		return "this is from get item function"
	pass
	
def action():
	return "play basketball this afternoon"	
	
	
if __name__ == "__main__":

	me = MyClass()
	setattr(me,"weather","it is sunshine")
	setattr(me,"event",action)

	print me.weather
	print me['event']
	print me.event()

 
<think>Hmm, the user is asking about the meaning of 'from collections import defaultdict' in Python. They've provided several references about defaultdict usage, which shows they've done some preliminary research but want a clear explanation. Looking at the references, they cover: - Basic defaultdict initialization with different types (int, set, str, list) - Comparison with traditional dict methods (if-else checks and setdefault) - Performance advantages - Context about collections module (deque vs list) The user seems to be at an intermediate Python level - they understand dicts but want to learn more efficient patterns. Their actual need is probably to: 1) Understand defaultdict's core functionality 2) See practical advantages over normal dicts 3) Know when to use it I notice they included defaultdict(int) for counting and defaultdict(list) for grouping examples in the references. That's good - I should highlight those classic use cases. The performance aspect (reference #2 mentioning "one less lookup") is also important to address. The challenge is explaining factory functions clearly. Maybe use the term "default value generator" instead since "callable" might confuse beginners. Should emphasize that defaultdict is still a dict subclass - just smarter about missing keys. Also worth mentioning: - The default_factory attribute - That regular KeyError behavior changes - Alternatives like setdefault() for comparison For the response structure: First explain the concept simply, then show before/after code comparisons from their references, finally summarize key benefits. The counting example (user_dict) is perfect for demonstration. Should avoid module history details (like deque comparisons) unless asked - focus solely on defaultdict. The user didn't ask about collections broadly. </think>Python中`from collections import defaultdict`语句的含义是**从collections模块导入defaultdict类,它创建了一个会为不存在的键自动生成默认值的特殊字典**。以下是详细解释: --- ### 一、核心功能 1. **自动初始化** 当访问不存在的键时,`defaultdict`会根据指定的**工厂函数**自动创建并初始化该键的默认值: ```python from collections import defaultdict dict_int = defaultdict(int) # 访问不存在的键时返回0 dict_list = defaultdict(list) # 访问不存在的键时返回空列表[] ``` 2. **避免KeyError** 普通字典访问不存在的键会报错,而`defaultdict`自动处理: ```python d = {} d['new_key'] += 1 # ❌ KeyError d_default = defaultdict(int) d_default['new_key'] += 1 # ✅ 自动初始化为0后+1,结果:1 ``` --- ### 二、与传统方法的对比 通过用户提供的引用示例说明优势[^2]: ```python # 传统方法 (需手动判断键是否存在) user_dict = {} users = ["a", "b", "a", "c"] for user in users: if user not in user_dict: user_dict[user] = 0 user_dict[user] += 1 # 需两次字典查询 # defaultdict方法 (自动初始化) dd = defaultdict(int) for user in users: dd[user] += 1 # ✅ 仅需一次操作 ``` - **效率更高**:减少一次键存在性检查 - **代码更简洁**:无需`if-else`或`setdefault()` --- ### 三、支持的工厂函数 | **初始化方式** | **默认值** | **典型用途** | |-----------------------|------------|----------------------| | `defaultdict(int)` | 0 | 计数器/频率统计 | | `defaultdict(list)` | [] | 分组存储(如邻接表) | | `defaultdict(set)` | set() | 去重集合存储 | | `defaultdict(str)` | "" | 字符串拼接 | --- ### 四、底层原理 1. 继承自Python内置的`dict`类 2. 重写`__missing__(key)`方法: 当键不存在时,调用工厂函数生成默认值并插入字典 3. 工厂函数必须是**可调用对象**(如`int`, `list`, 自定义函数等) --- ### 五、典型应用场景 1. **统计元素频率**(引用示例[^2]) ```python words = ["apple", "banana", "apple"] count = defaultdict(int) for word in words: count[word] += 1 # 输出: {'apple':2, 'banana':1} ``` 2. **分组数据存储** ```python data = [("A", 1), ("B", 2), ("A", 3)] groups = defaultdict(list) for key, value in data: groups[key].append(value) # 输出: {'A': [1,3], 'B': [2]} ``` 3. **构建图结构** ```python graph = defaultdict(list) edges = [(1,2), (1,3), (2,4)] for u, v in edges: graph[u].append(v) # 邻接表存储 ``` ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值