我试图弄清楚如何纠正错误,因为我不太清楚我是否理解错误发生了什么。
File "/Users/me/PycharmProjects/Project/project/main.py", line 15, in get
do = Player.pitcher()
TypeError: unbound method pitcher() must be called with Player instance as first argument (got nothing instead)
-
import webapp2
from pages import Page, ContentPage
from data import Player
class MainHandler(webapp2.RequestHandler):
def get(self):
page = Page()
content = ContentPage()
if self.request.GET:
id = self.request.GET['id']
type = self.request.GET['type']
name = self.request.GET['name']
if type == 'pitcher':
pitcher_data = [['1', '22', '2.41', '48', '24'], ['2', '16', '1.98', '61', '0'], ['3', '11', '5.18', '22', '0']]
do = Player.pitcher()
do.ip = ''....
self.response.write(page.print_out())
app = webapp2.WSGIApplication([
('/', MainHandler)
], debug=True)
class Player(object):
def __init__(self):
self.id = ''
self.player_name = ''
self.position = ''
def fielder(self):
self.bats = ''
self.throws = ''
self.avg = ''
self.hr = ''
self.rbi = ''
def pitcher(self):
self.ip = ''
self.era = ''
self.strikeouts = ''
self.walks = ''
self.sv = ''
答案 0 :(得分:1)
您在类对象pitcher
上调用Player
而不是该类的实例。
在Python中,实例化的类(对象)包含字典__dict__
形式的实例数据,当它在对象上调用时,它作为第一个参数self
传递给方法。
要按原样使用您的代码,正确的调用将是do = Player().pitcher()
这是链式调用的示例... Player()
创建并返回包含实例数据字典的Player对象的实例,.pitcher()
在新创建的实例上调用pitcher方法。
编辑: 再看一下你的示例代码,你可能想要做的就是创建两个不同的对象,这些对象继承了一些常见的状态。这可以使用子类来完成。
例如:
class Player(object):
def __init__(self):
self.id = ''
self.player_name = ''
self.position = ''
class Fielder(Player):
def __init__(self):
super(Fielder, self).__init__() # Call the constructor for the Player base class
self.bats = ''
self.throws = ''
self.avg = ''
self.hr = ''
self.rbi = ''
class Pitcher(Player):
def __init__(self):
super(Pitcher, self).__init__() # Call the constructor for the Player base class
self.ip = ''
self.era = ''
self.strikeouts =''
self.walks = ''
self.sv = ''
现在在您的主要代码中,您可以执行类似
的操作if type == 'pitcher':
player = Pitcher()
player.ip = <some value>
...
elif type == 'fielder':
player = Fielder()
player.bats = <some value>
... etc ...
答案 1 :(得分:0)
在调用函数之前将@staticmethod添加到投手函数或创建一个Player实例