我试图从类中的选项中选择一个随机对象,但我一直收到一个属性错误,我将给出必要的代码片段以及下面的具体错误:
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'”。请告诉我如何修复此问题
让我们假设每种车型都有自己的工厂。所以我们有一个卡车、轿车和货车工厂。这家工厂生产个人汽车并卖给你。当你想驾驶卡车时,你不会去卡车工厂问你的卡车在哪里。你应该知道你的卡车在哪里。它在你的房子前面
这里的对象和类也是一样的。你的
MaleShirt
类是汽车工厂。它生成MaleShirt
对象。您“购买”了三个MaleShirt
对象:maleshirt1
、maleshirt2
和maleshirt3
。当你想使用它们时,你必须知道它们在哪里,它们的名字是什么,而不是向工厂索要它们。然后,您可以将它们与名称一起“使用”:maleshirt1.explain()
,等等当你向工厂要它们时(
MaleShirt.maleshirt1()
),工厂告诉你它不知道它们在哪里因为它们属于你
我认为您对如何引用对象的实例感到困惑
maleshirt1
是一个实例必须是
MaleShirt
的类或静态方法您需要对象本身的内容,即
maleshirt1
(以及2和3)。因此,我们应该这样做
您还可以整理
explain
方法以打印字符串而不是元组if
语句实际上是不必要的,您只需要因为从
random.choice
返回的是MaleShirt
,因此有一个explain
方法相关问题 更多 >
编程相关推荐