Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 类中的可变变量_Python_List_Class_Global - Fatal编程技术网

Python 类中的可变变量

Python 类中的可变变量,python,list,class,global,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") 如何在不创建全局变量的

如果我有这样的课

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")

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

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

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)
产出:

['Michael', 'Sharon']
您可以尝试以下方法:

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']

但是,请注意,这本质上是一个全局变量。如果不想使用全局变量,则需要在单独的类中管理列表,提供一个
new\u person()
方法或类似方法,返回一个新的person并将其添加到列表中。(还请注意,您可能希望使用集合而不是列表。)等等。。。你怎么不加自我呢。创建列表时,您可以使用self访问名称列表。_name_list将人员存储在名为
Person
(单数)的类变量中,这看起来是一个相当糟糕的主意。创建一个新对象来存储
Person
objects@user13123因为实例可以访问类名称空间,所以有人能回答我的问题吗?不要这样做。类不应依赖于创建实例的方式和原因。
['name1', 'name2']