[英]Not getting an output when I call __str__ on a class instance?
I am just a beginner so be easy on me. 我只是一个初学者,所以请放轻松。 i was just playing with the
__str__
method and found that when I try to print the instance it just doesn't work 我只是在玩
__str__
方法,发现当我尝试打印实例时它根本不起作用
import random
brand = ("Samsung","Nokia","Sony","ATAT","Reliance")
no_of_sim = ("Dual-sim","Single-sim")
color = ("Blue","Violet","Orange","Green")
no_of_camera =("Front","Front-Back","Back")
no_of_cores = ("Dual Core","Quad Core","Octa Core")
additional = ("Bluetooth","NFS","Gps")
class mobile:
def __init__(self,**kwargs):
name = self
self.brand = random.choice(brand)
self.sim = random.choice(no_of_sim)
self.color = random.choice(color)
self.camera = random.choice(no_of_camera)
self.cores = random.choice(no_of_cores)
self.additional = random.choice(additional)
for key,value in kwargs.items():
setattr(self,key,value)
def __str__(self):
return "{} Is a {} color {} phone with {} facing cameras and it a {} with {}".format(self.__class__.__name__,self.color,self.brand,self.camera,self.cores,self,additional)
from mobile_phone import mobile
swiss = mobile()
print(swiss)
# It doesnt show up
There is a typo in the end of str method: str方法结尾有一个错字:
self,additional
It makes str method recursive. 它使str方法是递归的。 Changing "," to "."
将“,”更改为“。” removes the problem.
解决了问题。
You have a comma where you need a dot: 您需要在逗号处加点:
import random
brand = ("Samsung","Nokia","Sony","ATAT","Reliance")
no_of_sim = ("Dual-sim","Single-sim")
color = ("Blue","Violet","Orange","Green")
no_of_camera =("Front","Front-Back","Back")
no_of_cores = ("Dual Core","Quad Core","Octa Core")
additional = ("Bluetooth","NFS","Gps")
class mobile:
def __init__(self,**kwargs):
name = self
self.brand = random.choice(brand)
self.sim = random.choice(no_of_sim)
self.color = random.choice(color)
self.camera = random.choice(no_of_camera)
self.cores = random.choice(no_of_cores)
self.additional = random.choice(additional)
for key,value in kwargs.items():
setattr(self,key,value)
def __str__(self):
return("{} Is a {} color {} phone with "
"{} facing cameras and it a {} with {}".format(
self.__class__.__name__,
self.color,
self.brand,
self.camera,
self.cores,
self.additional)) # changed from self,additional
#from mobile_phone import mobile
swiss = mobile()
print(swiss)
Output: 输出:
mobile Is a Green color Reliance phone with Front-Back facing cameras and it a Dual Core with Bluetooth
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.