我在名为Weapons.py
的名为Pistol
的文件中有一个类,如下所示:
class Pistol(object):
MAXAMMO = 6
def __init__(self, ammo):
if(ammo <= self.MAXAMMO):
self.ammo = ammo
def shoot(self):
if(ammo > 0):
accuracy = random.randint(0, 3)
return 3 * accuracy
ammo -= 1
else:
print("No ammo")
一个名为ColtM1911
的类继承自Pistol
。它看起来像这样:
class ColtM1911(Pistol):
MAXAMMO = 7
def __init__(self, ammo):
self.ammo = 7
当我跑步时:
import Player
import SetUp
from Utils import *
import pickle
import TitleAnimation
import os
import SaveLoad
from Weapons import *
gun = ColtM1911(5)
在另一个文件中,它给了我"TypeError: object() takes no parameters"
在shell中尝试这个时它起作用了,所以我怀疑这是将它放在一个单独的文件中。
完整的追溯是,
Traceback (most recent call last):
File "C:\Users\James\Documents\game.py", line 3, in <module>
gun = Weapons.ColtM1911(5)
TypeError: object() takes no parameters
答案 0 :(得分:2)
我可以重新创建错误的唯一方式是Pistol
实际定义为:
class Pistol(object()):
# ^ note extraneous parentheses
在Python 3.x中,您根本不需要object
;默认情况下,所有类都是新式的。此外,还存在逻辑错误,M1911.__init__
是多余的。尝试类似:
import random
class Pistol:
MAXAMMO = 6
def __init__(self, ammo):
if ammo <= self.MAXAMMO:
self.ammo = ammo
else:
# what do you want do do here? Raise an error? Set ammo = MAXAMMO?
def shoot(self):
if self.ammo > 0:
self.ammo -= 1
return 3 * random.randint(0, 3)
else:
print("No ammo")
class ColtM1911(Pistol):
MAXAMMO = 7