类中的可变变量

时间:2017-12-02 22:43:34

标签: python list class global

如果我有这样的课程。

class Person():

def __init__(self, name):
    self._name = name
    self._name_list = []
    if(self._name not in self._name_list):
        self._name_list.append(self._name)
father = Person("Michael")
mother = Person("Sharon")
>>>self._name_list

["Michael", "Sharon"]

如何在不创建全局变量的情况下执行此操作?每次我实例化一个新人时,它都会创建自己的列表。但是我需要在每个创建新人时附加名称的类范围内的列表。

2 个答案:

答案 0 :(得分:1)

您可以将其保存在类本身中,如下所示:

var opt = {
  url: 'https://tartan.plaid.com/connect',
  form: {
    // ...
  }
};

request.post(opt, function (error, response, body) {
  console.log(body)
});

输出:

class Person():
    _name_list = []

    def __init__(self, name):
        self._name = name
        if self._name not in self._name_list:
            self._name_list.append(self._name)

father = Person("Michael")
mother = Person("Sharon")

print(Person._name_list)

答案 1 :(得分:0)

你可以试试这个:

people = []
class Person():
   def __init__(self, name):
       self._name = name
       if self._name not in people:
           global people
           people.append(self._name)

person = Person('name1')
person1 = Person('name2')
print(people)

输出:

['name1', 'name2']