【问题标题】:python 2.7 or 3.2(classes and instances)python 2.7 或 3.2(类和实例)
【发布时间】:2014-06-12 07:10:04
【问题描述】:

我是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 的属性的错误。

我该怎么办?

【问题讨论】:

    标签: python-2.7 python-3.2


    【解决方案1】:

    这只是一个摘要,遗漏了很多内容,但基本上,您的 num 应该作为 self.num 进入 __init__() 调用。所以:

    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.")) 语句),它将失败,您将不明白为什么。

    讨论“类变量”和“实例变量”之间的区别的原因,但你可能还为时过早与这个概念搏斗。不过,可能值得一看 the Python tutorial's chapter on classes。如果您不理解该教程的某些部分,请不要担心——只需学习一些概念,继续编写代码,然后稍后再返回并再次阅读教程,您可能会清楚更多概念.

    祝你好运!

    【讨论】:

    • @user3732914 - 如果您有单独的问题,最好将其作为一个全新的问题提出。 StackOverflow 将 cmets 限制为大约 500 个字符,并且不允许访问代码格式。我建议发布一个新问题,然后在此处的 cmets 中添加指向它的链接。
    【解决方案2】:

    这里有很多问题:

    1. num = int(input(...)) 分配一个 class 属性 - 此代码在定义类时运行,not 在创建实例时运行,并且该属性将由该类的所有实例共享;
    2. 尽管为__init__ 定义了第二个num 参数,但您调用pallavi = supermarket() 而不传递参数;
      1. 还有,为什么numodd_even的参数——如果是属性,通过self访问;和
    3. 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

    【讨论】:

    • @jonrsharpe ....我明白了并尝试以相同的方式进行...但它仍然显示错误...我将 dat 代码放入我提出的另一个问题中..请回答..关于...sriparna
    猜你喜欢
    • 1970-01-01
    • 2017-11-23
    • 2016-12-03
    • 2011-08-21
    • 2012-01-13
    • 1970-01-01
    • 2012-11-28
    • 2013-04-11
    • 1970-01-01
    相关资源
    最近更新 更多