Python中如何在一个类中访问或使用另一个类的实例属性
Python类间访问实例属性的实现方法
你要实现的需求有两种常用的实现方案,核心逻辑是:不同类的实例是相互独立的,必须将House类的具体实例传递给Paint类,才能访问到对应实例的尺寸属性。
方案1:初始化Paint实例时绑定对应House实例
适合单款油漆固定对应某一个房屋的场景,初始化时直接算出总价:
class House: # 原代码此处漏写冒号,已补充 def __init__(self, length, width): self.length = length self.width = width class Paint: # 新增入参house,用于接收House类的实例 def __init__(self, color_paint, unit_price, house): self.color_paint = color_paint # 通过传入的house实例获取长宽计算总价 self.total_price = unit_price * (house.length * house.width) # 实际调用示例 my_house = House(10, 8) my_paint = Paint("米白色", 25, my_house) print(my_paint.total_price) # 输出结果:2000
方案2:单独定义价格计算方法
适合同一款油漆需要给多个不同房屋计算成本的场景,灵活度更高:
class House: def __init__(self, length, width): self.length = length self.width = width class Paint: def __init__(self, color_paint, unit_price): self.color_paint = color_paint self.unit_price = unit_price # 调用计算方法时传入对应房屋实例即可 def calc_total_price(self, house): return self.unit_price * house.length * house.width # 实际调用示例 my_house = House(10, 8) parents_house = House(12, 9) white_paint = Paint("白色", 20) print(white_paint.calc_total_price(my_house)) # 输出1600 print(white_paint.calc_total_price(parents_house)) # 输出2160
注意事项
- 不要直接在Paint类中全局调用House类的属性,每个House实例的尺寸都是独立的,只有传递具体实例才能拿到对应的值
- 类名遵循Python编码规范建议首字母大写,和普通变量、函数做区分
- 原代码中House类的
__init__方法定义末尾漏写冒号,属于基础语法错误,运行前需要修正
内容的提问来源于stack exchange,提问作者Matly
相关产品推荐
相关产品推荐

