2015-04-15 5 views
1

Я пытаюсь создать подкласс Thing под названием Openable. При определении метода __init__(), я получаюОшибка типа в классах

type error: Traceback (most recent call last): 
    File "/Users/jaredbanton8/Documents/things.py", line 57, in <module> 
    book1 = Openable("Necronomicon", "book shelf") 
    File "/Users/jaredbanton8/Documents/things.py", line 40, in __init__ 
    super().__init__(name) 
TypeError: __init__() missing 1 required positional argument: 'location' 

В моем коде, я включал тесты для моих классов. Я не уверен, что вызывает эту ошибку. Мой код:

class Thing: 
     """a class for representing physical objects in a game 

     attributes: name (str), location (str)""" 
     def __init__(self, name, location): 
      """assigns values to attributes""" 
      self.name = name 
      self.location = location 

     def description(self): 
      """returns str that describes the state of the object 

      str -> str""" 
      return str('Nothing special.') 
    def test(t): 
     """Tests the name, location, and description method of t 

     Thing -> None""" 
     print(t.name + " (" + t.location + "): " + t.description()) 


key1 = Thing("golden key", "under door mat") 
test(key1) 

key2 = Thing("rusty key", "jacket pocket") 
test(key2) 

    class Openable(Thing): 
     """a class for representing those physical objects which can be opened 

     inherited attributes: all""" 
     def is_open(t): 
      """returns a bool whether the object is open or not 

      str -> bool""" 
      if is_open(t): 
       return True 
     def __init__(self, name, location, o=0): 
      """assigns values to attributes""" 
      super().__init__(name) 
      super().__init__(location) 
      is_open = o 

def test_open(o): 
    """Tests an attempt to open o 

    Openable -> None""" 
    print() 
    test(o) 
    print("Attempting to open the " + o.name + "...") 
    if o.try_open(): 
     print("The " + o.name + " should now be open.") 
    else: 
     print("The " + o.name + " should now be closed.") 
    test(o) 

book1 = Openable("Necronomicon", "book shelf") 
test_open(book1) 

window1 = Openable("side window", "north wall", True) 
test_open(window1) 

ответ

7

__init__ из class Thing нужны два аргумента. В __init__ из class Openable заменить

super().__init__(name) 
super().__init__(location) 

с

Код выше будет работать в Python 3.x. В Python 2.x вам нужно

super(Openable, self).__init__(name, location) 

или

Thing.__init__(self, name, location) 

Функция is_open() в class Openable, вероятно, должен выглядеть

 def is_open(): 
      return self.isOpen 

     def __init__(self, name, location, o=False): 
      super().__init__(name, location) 
      self.isOpen = o 

и использовали

if o.is_open(): 
    print("The " + o.name + " should now be open.") 
else: 
    print("The " + o.name + " should now be closed.") 
+1

Я думаю, вы имели в виду 'Thing .__ init __ (self, name, location)', иначе он даст бесконечный цикл. – Arkanosis

+0

любые предложения о том, как исправить def is_open (t)? – holaprofesor

+0

@ Арканоз Вы правы, спасибо. – kvorobiev

8

Вы должны вызвать __init__ один раз с двумя аргументами, а не в два раза с одним аргументом:

Кроме того, если вы используете Python 2, super также потребует некоторые аргументы:

super(Openable, self).__init__(name, location) 
+2

Вопрос помечен python-3.x: первый синтаксис действителен в Python 3. –

+2

«Кроме того,' super' также нуждается в некоторых аргументах »- в Python 3 на самом деле этого не происходит. Им пришлось сделать некоторые странные вещи с помощью компилятора, чтобы заставить его работать. – user2357112

+0

Я пропустил тег, спасибо! :) – Arkanosis

Смежные вопросы