我在任何地方都找不到解决方案,但是当我在脚本中调用方法函数时,我在父类(Wallet)中使用了一个方法来打印类的名称。
问题是,即使我创建了一个“Pen”类来继承“Wallet”类的属性和方法,该名称仍然显示为父类的名称。
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__.__name__
来指代类本身的名称。
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")
然后我创建了这个 pen 类来继承与 Wallet 类相同的属性和方法。
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
即使对于 Pen 类,它也使用 Wallet 的类名。我期待它是“笔”(笔的尺寸很小......)有什么想法吗?
如果我只调用属性的实例并手动打印结果(如下所示),它就可以工作,但我只是出于好奇而想这样做。
for item in [mywallet,mypen]:
print(f"The colour of the {item.__class__.__name__} is "+item.colour+".",
f"The material of the {item.__class__.__name__} is "+item.material+".")
不要使用特殊变量
__class__
,该变量的全部目的是提供定义该方法的类。它的存在是为了支持 super
的零参数形式。用途:
type(self).__name__
或同等的
self.__class__.__name__