如何创建含默认属性的Python类:直接调用实例返回默认值
实现自定义默认属性的Cell类
要实现你需要的效果,无需继承int或str,只需在普通类中实现必要的特殊方法,控制实例的行为,同时保留自定义属性。以下是完整实现:
class Cell: def __init__(self, x, y, value): self.x = x self.y = y self.value = value # 控制print()和字符串插值的显示内容 def __str__(self): return str(self.value) # 控制容器(如列表)、调试信息的显示内容 def __repr__(self): return repr(self.value) # 让sum()能将实例转换为整数 def __int__(self): return int(self.value) # 让sum()支持浮点类型的value(可选) def __float__(self): return float(self.value) # 支持需要整数索引的场景(如切片,可选) def __index__(self): return int(self.value) # 当value是可计算长度的类型时,支持len()调用 def __len__(self): return len(self.value)
关键方法说明
每个特殊方法对应你需要的一项功能:
__str__&__repr__:直接打印实例或在列表/组合中显示时,自动返回value的内容,无需手动调用.value。__int__/__float__:让sum()等内置函数能正确识别实例的数值,内部会自动调用这些方法完成类型转换。__len__:当value是字符串、列表等有长度的对象时,调用len(cell)会返回value的长度。- 不实现
__add__/__sub__等运算符方法:避免两个Cell实例意外执行加减操作,完全符合你“不继承内置类型全部方法”的需求。
验证你的测试场景
运行以下代码即可实现你想要的效果:
# 测试单个数值型Cell i = Cell(5, 3, 17) print(i) # 输出:17 print(f"点({i.x}, {i.y})的数值为{i}") # 输出:点(5, 3)的数值为17 # 测试字符串型Cell s = Cell(7, 9, "red") print(s) # 输出:red print(len(s)) # 输出:3 print(s.x, s.y) # 输出:7 9 # 测试sum()处理Cell列表 intarr = [Cell(1, 2, 17), Cell(3, 4, 11), Cell(5, 6, 21)] print(intarr[0]) # 输出:17 print(intarr[0].x, intarr[0].y) # 输出:1 2 print(sum(intarr)) # 输出:49 # 测试itertools.combinations处理Cell列表 from itertools import combinations strarr = [Cell(1, 2, "bob"), Cell(3, 4, "joe"), Cell(5, 6, "ted")] print(strarr[0]) # 输出:bob print(len(strarr[0])) # 输出:3 print(strarr[0].x, strarr[0].y) # 输出:1 2 print(list(combinations(strarr, 2))) # 输出:[('bob', 'joe'), ('bob', 'ted'), ('joe', 'ted')]
额外说明
- 如果你的
value是其他类型(如列表、字典),只需调整对应特殊方法即可适配,比如__len__会自动处理列表的长度。 - 尝试对两个
Cell实例执行加法操作会抛出TypeError,完全避免了继承内置类型带来的多余方法。
内容的提问来源于stack exchange,提问作者gskluzacek
相关产品推荐
相关产品推荐

