Python子类继承父类后,调用父类方法时类名显示异常求助
问题:子类调用父类方法时显示父类名称而非子类名称
在父类Wallet中定义了打印类名的方法,但子类Pen继承后调用这些方法,输出的仍是父类名称而非子类名称。
相关代码如下:
父类代码:
class Wallet(): def __init__(self,colour,size,material,cost): print("A Wallet Object Class has been made") self.colour = colour self.size = size self.material = material self.cost = cost def colour_call(self): print(f"The colour of the {__class__.__name__} is {self.colour}") def size_call(self): print(f"The size of the {__class__.__name__} is {self.size}") def material_call(self): print(f"The material is made of {self.material}") def cost_call(self): print(f"The cost of the {__class__.__name__} is {self.cost}")
子类代码:
class Pen(Wallet): def __init__(self, colour, size, material, cost): super().__init__(colour, size, material, cost) print(f"A {__class__.__name__} Object Class has inherited from the Wallet Class")
测试代码:
mywallet = Wallet(colour = "red", size = "Large", material = "leather", cost = 2.50) mypen = Pen(colour = "blue", size = "small", material = "aluminium", cost = 1.50) for item in [mywallet,mypen]: item.colour_call() item.size_call() item.material_call()
当前输出:
The colour of the Wallet is red The size of the Wallet is Large The material is made of leather The colour of the Wallet is blue The size of the Wallet is small The material is made of aluminium
期望输出中,mypen的相关打印应该显示Pen而非Wallet。
解决思路
问题出在__class__.__name__的使用上:在父类方法中,__class__指向的是定义该方法的类(也就是Wallet),而非当前实例所属的类。要获取实例实际所属的类名,应该用self.__class__.__name__——self指向当前调用方法的实例,self.__class__就是该实例对应的类,这样就能动态获取父类或子类的名称。
修改后的父类方法代码:
class Wallet(): def __init__(self,colour,size,material,cost): print("A Wallet Object Class has been made") self.colour = colour self.size = size self.material = material self.cost = cost def colour_call(self): print(f"The colour of the {self.__class__.__name__} is {self.colour}") def size_call(self): print(f"The size of the {self.__class__.__name__} is {self.size}") def material_call(self): print(f"The material is made of {self.material}") def cost_call(self): print(f"The cost of the {self.__class__.__name__} is {self.cost}")
再次运行测试代码,输出就会符合预期:
A Wallet Object Class has been made A Wallet Object Class has been made A Pen Object Class has inherited from the Wallet Class The colour of the Wallet is red The size of the Wallet is Large The material is made of leather The colour of the Pen is blue The size of the Pen is small The material is made of aluminium
内容的提问来源于stack exchange,提问作者Dsafsfa
相关产品推荐
相关产品推荐

