【问题标题】:Wrapping code in a Class Python在 Python 类中包装代码
【发布时间】:2016-06-29 11:53:59
【问题描述】:

我是一名 Python 初学者,我想将我的代码封装在一个类中。但是,当我运行代码时,我得到一个 AttributeError:'Generating_objects' 对象没有属性 'pick_type'。请告诉我哪里错了?

import random
from random import choice

class Generating_objects(object):
      """This class would be used to generate objects of different types e.g 
          integers, string, lists and so on"""


    def __init__(self):
        pass



    def generateRandomInt(self):
        self.num = random.randint(-100000, 1000000000)
        return self.num



    def pick_type(self):

       lists = ["Int","String","Float","bool"]

       choices = choice(lists)


       if choices == "Int":
          print generateRandomInt()
       else:
          print "BOO"

genR = Generating_objects()
genR.pick_type()

【问题讨论】:

  • 上面的缩进是否与您的代码中的内容匹配?
  • 然后点击edit按钮,再次复制粘贴你的代码,选择代码,然后点击工具栏上的{ }按钮。 ;)
  • 您问题中的代码与您正在运行的代码不匹配。您问题中的代码会给出 IndentationError.
  • 您是否尝试省略了初始化声明?我猜,pass 甚至中断了父 object 类的初始化,所以你的类根本没有属性
  • 我试过你的代码 - 它不会抛出错误,只是打印 BOO

标签: python python-2.7


【解决方案1】:

Python 对缩进敏感。您的方法需要在类内缩进(即比类声明更远):

class Generating_objects(object):
  """This class would be used to generate objects of different types e.g 
      integers, string, lists and so on"""

  def __init__(self):
    pass
    ...

  def pick_type(self):
    ...

【讨论】:

  • 您的代码也有缩进错误 - """docstrings""" 也必须与方法在同一级别缩进。
【解决方案2】:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-14
    • 1970-01-01
    • 2011-08-10
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    相关资源
    最近更新 更多