AttributeError:object没有属性(来自书籍“Python CRASH COURSE”的例子)

时间:2015-09-18 05:34:26

标签: python

我刚开始学习python几天前,我读的那本书是“Python CRASH COURSE”

我不知道我在这段代码中遗漏了什么,请帮助我!

class mathfunctions:
  def addition(self,num1,num2):
      return num1+num2
  def subtraction(self,num1,num2):
      return num1-num2
  def multiply(self,num1,num2):
      return num1*num2
  def divide(self,num1,num2):
      return num1/num2
class actiondeclarer():
  action = None
  x = None
  y = None
  functions = mathfunctions()
  def __init__(self,actionnum,num1,num2):
      self.action = actionnum
      self.x = num1
      self.y = num2
      self.actionpicking()
      def actionpicking(self):
         if self.action is 1:
             print("sum is ",self.functions.addition(self.x,self.y))
         elif self.action is 2:
             print("difference is ",self.functions.subtraction(self.x,self.y))
         elif self.action is 3:
             print("multitude is ",self.functions.multiply(self.x,self.y))
         elif self.action is 4:
             print("divide is ",self.functions.divide(self.x,self.y))
         else:
            print("invalid")

checker = actiondeclarer(1,5,10)

错误消息是AttributeError:'actiondeclarer'对象没有属性'actionpicking'

顺便说一句,如果代码是正确的,结果“总和是15”可以显示而无需输入print(checker),对吧?

1 个答案:

答案 0 :(得分:2)

你的缩进已经关闭。

def __init__(self,actionnum,num1,num2):
  # Code
  self.actionpicking()
  def actionpicking(self):
     # Code

这在__init__内本地定义了一个闭包。您希望actionpicking的缩进级别与__init__的缩进级别匹配。

def __init__(self,actionnum,num1,num2):
  # Code
  self.actionpicking()
def actionpicking(self):
  # Code