在类实例上调用__str__时没有得到输出?

时间:2016-08-08 14:08:46

标签: python

我只是一个初学者,所以对我来说很容易。我刚刚玩__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

2 个答案:

答案 0 :(得分:1)

str 方法结尾有一个拼写错误:

self,additional

使 str 方法递归。将“,”更改为“。”消除了这个问题。

答案 1 :(得分:0)

你有一个逗号,你需要一个点:

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)

输出:

mobile Is a Green color Reliance phone with Front-Back facing cameras and it a Dual Core with Bluetooth