簡體   English   中英

在類實例上調用__str__時未得到輸出?

[英]Not getting an output when I call __str__ on a class instance?

我只是一個初學者,所以請放輕松。 我只是在玩__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

str方法結尾有一個錯字:

self,additional

它使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))  # 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM