我是python的初学者。我的问题是在使用python编译项目时,如何使用户输入变量成为属性。
例如:
class supermarket:
num=int(input('enter a no.'))
def __init__(self,num):
self.ini=''
def odd_even(self,num):
if num%2==0:
self.ini='even'
else:
self.ini='odd'
#calling
pallavi=supermarket()
pallavi.(num)
此处,它显示的错误是没有名为num
的属性。
我该怎么办?
答案 0 :(得分:1)
这只是一个摘要并留下了很多,但基本上,您的num
应该作为__init__()
进入self.num
来电。所以:
class supermarket:
def __init__(self):
self.ini = ''
self.num = int(input('enter a no.'))
# etc.
然后访问属性:
pallavi = supermarket()
pallavi.num # No parentheses needed
Python中的课程还有很多,我现在还没有时间进入,但我会触及一件事:直到你知道你在做什么,类中的所有赋值都应该放在函数内部,而不是放在类定义本身中。如果你的语句中有一个带有=符号的语句,而不是一个函数(比如你的例子中的num=int(input("enter a no."))
语句),那么它会失败并且你赢了# 39;不明白为什么。
之所以进入"类变量之间的差异"和"实例变量",但你可能要太早与这个概念搏斗。不过,可能值得一看the Python tutorial's chapter on classes。如果您不理解该教程的部分内容,请不要担心它 - 只需学习一些概念,继续编写代码,然后再返回并再次阅读教程,可能还需要了解其他一些概念。对你很清楚。
祝你好运!答案 1 :(得分:0)
这里有很多问题:
num = int(input(...))
分配类属性 - 此代码在定义类时运行, not 在创建实例时运行,属性将由所有类的实例; num
定义了第二个__init__
参数,但在不传递参数的情况下调用pallavi = supermarket()
;
num
是odd_even
的参数 - 如果它是属性,请通过self
访问它;和pallavi.(num)
不正确Python语法 - 属性访问语法为object.attr
,括号为SyntaxError
。我认为你想要的是:
class Supermarket(): # note PEP-8 naming
# no class attributes
def __init__(self, num):
self.num = num # assign instance attribute
self.ini = 'odd' if num % 2 else 'even' # don't need separate method
@classmethod # method of the class, rather than of an instance
def from_input(cls):
while True:
try:
num = int(input('Enter a no.: ')) # try to get an integer
except ValueError:
print("Please enter an integer.") # require valid input
else:
return cls(num) # create class from user input
这将用户输入的请求与实例的实际初始化分开,并将被称为:
>>> pallavi = Supermarket.from_input()
Enter a no.: foo
Please enter an integer.
Enter a no.: 12
>>> pallavi.num
12
>>> pallavi.ini
'even'
正如您提到的3.2和2.7,请注意在使用2.x时input
应替换为raw_input
。