设置器和获取器 python

Setters and Getters python

我环顾四周,但我尝试的一切似乎都没有得到任何结果。我只需要为 class 设置自定义 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) 是否合法,但这似乎是从 class.

内部调用函数的唯一方法

__init__(self, type) -> "type" 中作为数字传递,它应该被转换并存储为字符串,而不是在调用 getter 时重新转换为数字. (也许有更好的方法 - 使用外部字典进行转换并仅存储数字..?

希望已经足够清楚了。

您可以使用 @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__ 应该总是 return 一个字符串;你 return 是一个元组。您的错误是由您的 self.type() 调用引起的;因为 self.type 在您的代码中存储了一个字符串,您试图将该字符串视为可调用的。

可以从__init__调用其他函数(class之外);它实际上只是您实例上的另一种方法,只需考虑已经设置和尚未设置的属性即可。但是,如果该函数依赖于 self 上的信息并且在 class 之外没有用处,我会将其移动到 class 中并带有 _ 前缀以表明它是 class 实现的内部。