我环顾四周,但我尝试的一切似乎都没有得到任何结果。我只需要为一个将数字转换为字符串的类设置自定义 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 时重新转换为数字. (也许有更好的方法 - 使用外部字典进行转换并仅存储数字..?
PS1:调用外部函数
random_row(board, self)
和random_col
传递self
是否合法,即使它是没有正确初始化,或者我应该将函数作为另一个 setter 移到类中吗?PS2:调用
__repl__
:def __repr__(self): return "Ship. Type: ", str(self.get_type()), str(self.type())
返回:
Traceback (most recent call last): File "/Users/xx/Documents/python/battleship/battleship.py", line 85, in <module> print ship.__repr__() File "/Users/xx/Documents/python/battleship/battleship.py", line 74, in __repr__ return "Ship. Type: ", str(self.get_type()), str(self.type()) TypeError: 'str' object is not callable
仅在
get_type()
上调用它def __repr__(self): return "Ship. Type: ", str(self.get_type())
返回:
Type: Submarine ('Ship. Type: ', '2')
希望它足够清楚。
最佳答案
您可以使用 @property
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
的信息并且在类之外没有用处,我会将它移到带有 _
前缀的类中以表明它是内部的到类实现。
关于python - setter 和 getter python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28044902/