我环顾四周,但我试过的每一件事似乎都没有得到任何结果。我只需要为一个将数字转换为字符串的类设置一个自定义setter和getter,反之亦然。因为python不支持我用的字典。
class Ship(object):
def __init__(self, type):
self.fixed = define_direction()
self.row = random_row(board, self)
self.col = random_col(board, self)
self.type = self.set_type(type)
print "Type:", str(self.type)
def set_type(self, type):
return {
0 : "Patrol boat",#2
1 : "Destroyer",#3
2 : "Submarine",#3
3 : "Battleship",#4
4 : "Aircraft carrier",#5
}.get(type, "Patrol boat")
def get_type(self):
return {
"Patrol boat" : 0,#2
"Destroyer" : 1,#3
"Submarine" : 2,#3
"Battleship" : 3,#4
"Aircraft carrier" : 4,#5
}.get(self.type, 0)
def __repr__(self):
return "Ship. Type: ", self.get_type()不太确定self.type = self.set_type(type)是否合法,但似乎是从类中调用函数的唯一方法。
在__init__(self, type) ->中,"type“作为一个数字传递,它应该作为一个字符串进行转换和存储,而不是在调用getter时被重新转换为一个数字。(也许有一种更好的方法-使用外部字典进行转换并存储数字。)
random_row(board, self)和传递self的random_col是合法的,即使它没有正确初始化,还是应该将函数作为另一个设置器移到类中?__repl__:
def __repr__(self):返回"Ship. Type:",str(self.get_type()),str(self.type())
返回:
回溯(最近一次调用):文件"/Users/xx/Documents/python/battleship/battleship.py",行85,打印ship.__repr__()文件"/Users/xx/Documents/python/battleship/battleship.py",行74,在__repr__中返回"Ship.“类型:,str(self.get_type()),str(self.type()) TypeError:'str‘对象不可调用
只在get_type()上调用它
def __repr__(self):返回"Ship. Type:",str(self.get_type())
返回:
类型:潜艇(“船”,类型:“,”2“)希望一切都足够清楚。
发布于 2015-01-20 12:05:27
您可以使用 decorator来管理type属性:
class Ship(object):
def __init__(self, type):
self.fixed = define_direction()
self.row = random_row(board, self)
self.col = random_col(board, self)
self.type = type
print "Type:", str(self.type)
@property
def type(self):
return {
"Patrol boat": 0,
"Destroyer": 1,
"Submarine": 2,
"Battleship": 3,
"Aircraft carrier": 4,
}.get(self._type, 0)
@type.setter
def type(self, type):
self._type = {
0: "Patrol boat",
1: "Destroyer",
2: "Submarine",
3: "Battleship",
4: "Aircraft carrier",
}.get(type, "Patrol boat")
def __repr__(self):
return "Ship. Type: " + self._type您的__repr__应该始终返回一个字符串,而不是返回一个元组。您的错误是由您的self.type()调用引起的;由于self.type在代码中存储了一个字符串,所以您试图将该字符串视为可调用的。
可以从__init__调用其他函数(类之外);它只是实例上的另一种方法,只需考虑哪些属性已经设置,哪些属性尚未设置。但是,如果函数依赖于self上的信息,并且在类之外没有任何用途,我会将它移到带有_前缀的类中,以表明它是类实现的内部。
https://stackoverflow.com/questions/28044902
复制相似问题