[英]Creating a list using private variables in a class
I am creating a class called Pet
.我正在创建一个名为Pet
的类。 I am making my variables private so no one can modify them (ensuring encapsulation).我将我的变量设为私有,因此没有人可以修改它们(确保封装)。 I want to create a list using private variables.我想使用私有变量创建一个列表。 Then I want to be able to call my pet_list
list outside the class where I will be using it for a later purpose (would I need to create a getter for my list inside the Pet
class to do this?).然后,我希望能够在类外调用我的pet_list
列表,我将在以后使用它(我是否需要在Pet
类中为我的列表创建一个 getter 来执行此操作?)。
I am new to python but I'm trying to code using the object orientated principles.我是 python 的新手,但我正在尝试使用面向对象的原则进行编码。
This is my code so far.到目前为止,这是我的代码。 I'm thinking because my pet
variable is private I need to use a setter to set the Pet
s in the list?我在想,因为我的pet
变量是私有的,所以我需要使用 setter 来设置列表中的Pet
? But I get this error when I want to print set_pet() missing 1 required positional argument: 'pet'
.但是当我想打印set_pet() missing 1 required positional argument: 'pet'
时出现此错误set_pet() missing 1 required positional argument: 'pet'
。
class Pet:
def __init__(self, pet ):
self.pet = pet
def set_pet(self, pet):
self.__pet = pet
def get_pet(self):
return self.__pet
#creating list
pet_list = []
p = Pet
pet_list.append(p.set_pet("cat"))
pet_list.append( Pet("dogs"))
pet_list.append( Pet("fish"))
pet_list.append( Pet("horses"))
pet_list.append( Pet("birds"))
for obj in pet_list:
print(obj.pet)
The problem is at p = Pet
.问题在于p = Pet
。 Here you are not initializing an instance of the class Pet
but you are instead setting p
equal to the class.在这里,您不是在初始化Pet
类的实例,而是将p
设置为等于该类。 Instead use而是使用
p = Pet("The pet you want")
The reason you are getting the errror set_pet() missing 1 required positional argument: 'pet'
is because "cat"
is being passed as a positional argument in the place of self
and thus it is as if you passed only 1 argument.您得到错误set_pet() missing 1 required positional argument: 'pet'
是因为"cat"
作为位置参数代替self
传递,因此就好像您只传递了 1 个参数。
Also, pet_list.append(p.set_pet("cat"))
would append None
into the list since you are only setting the property and not returning anything, all the other's should work fine as expected.此外, pet_list.append(p.set_pet("cat"))
会将None
附加到列表中,因为您只是设置属性而不返回任何内容,所有其他的都应该按预期正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.