在尝试从类中随机选择对象时不断接收错误

2024-10-01 00:17:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从类中的选项中选择一个随机对象,但我一直收到一个属性错误,我将给出必要的代码片段以及下面的具体错误:

import random

#creating male shirt class
class MaleShirt():
    temp = ""
    style = ""

    def __init__(self, temp, style):
        self.temp = temp
        self.style = style
        return None

    #setters and getters
    def setTemp(self, temp):
        self.temp = temp

    def getTemp(self):
        return self.temp

    def setStyle(self, style):
        self.style = style

    def getStyle(self):
        return self.style

    def explain(self):
        print('Wear a', self.getStyle(), 'shirt when it is', self.getTemp(), 'outside')

#classifying shirts
maleshirt1 = MaleShirt('hot', 'boho')
maleshirt2 = MaleShirt('cold', 'preppy')
maleshirt3 = MaleShirt('hot', 'hipster')

#randomly choosing shirt (where I get the error)
choice = random.choice(MaleShirt.maleshirt1(), MaleShirt.maleshirt2(), MaleShirt.maleshirt3())
if choice == MaleShirt.maleshirt1():
    maleshirt1.explain()
if choice == MaleShirt.maleshirt2():
    maleshirt2.explain()
if choice == MaleShirt.maleshirt3():
    maleshirt3.explain()

每次收到的属性错误都会告诉我“type object'MaleShirt'没有属性'maleshirt1'”。请告诉我如何修复此问题


Tags: selfreturnif属性styledef错误temp
2条回答

让我们假设每种车型都有自己的工厂。所以我们有一个卡车、轿车和货车工厂。这家工厂生产个人汽车并卖给你。当你想驾驶卡车时,你不会去卡车工厂问你的卡车在哪里。你应该知道你的卡车在哪里。它在你的房子前面

这里的对象和类也是一样的。你的MaleShirt类是汽车工厂。它生成MaleShirt对象。您“购买”了三个MaleShirt对象:maleshirt1maleshirt2maleshirt3。当你想使用它们时,你必须知道它们在哪里,它们的名字是什么,而不是向工厂索要它们。然后,您可以将它们与名称一起“使用”:maleshirt1.explain(),等等

当你向工厂要它们时(MaleShirt.maleshirt1()),工厂告诉你它不知道它们在哪里

type object 'MaleShirt' has no attribute 'maleshirt1'

因为它们属于你

我认为您对如何引用对象的实例感到困惑

maleshirt1 = MaleShirt('hot', 'boho')

maleshirt1是一个实例

MaleShirt.maleshirt1()

必须是MaleShirt的类或静态方法

您需要对象本身的内容,即maleshirt1(以及2和3)。
因此,我们应该这样做

choice = random.choice([maleshirt1, maleshirt2, maleshirt3])
if choice == maleshirt1:
    maleshirt1.explain()
elif choice == maleshirt2:
    maleshirt2.explain()
elif choice == maleshirt3:
    maleshirt3.explain()

您还可以整理explain方法以打印字符串而不是元组

def explain(self):
        print('Wear a %s shirt when it is %s outside' % (self.style, self.temp))

if语句实际上是不必要的,您只需要

choice.explain()

因为从random.choice返回的是MaleShirt,因此有一个explain方法

相关问题 更多 >