在类属性中嵌入一个列表并调用它的值

And*_*y.l 0 python class list

如果我有以下课程:

class theater:
    def __init__(self):
        self.__seatMatrix=[10]*5
        self.__seats=seating[0]
        self.__rows=len(seating)
Run Code Online (Sandbox Code Playgroud)

如何实现get/setter来更新席位值?座位= [10]*5,5行,10个座位.在整个周末,我一直在转过头.当我尝试:

def getseats(self):
        self.__seats
Run Code Online (Sandbox Code Playgroud)

它没有返回任何东西.

/安迪

Jar*_*die 5

不要忘记函数实现中的return语句.与其他一些语言不同,Python不会自动返回函数中计算的最后一个表达式.来自没有return语句的函数的返回值是None.

在这种情况下,您的getseats()方法应该是:

def getseats(self):
    return self.__seats
Run Code Online (Sandbox Code Playgroud)

顺便说一句,如果你想将类中的某些变量指定为半私有(我说半完全私有变量并不存在),Python中的约定是使用单个下划线(self._seats而不是self.__seats).以双下划线为前缀的实例变量实际上会损坏名称以尝试强制将其指定为私有,如果这不是您想要的,则会产生令人惊讶的结果.

python文档解释得最好:http://docs.python.org/tutorial/classes.html#private-variables