提问人:Alex Rapino 提问时间:6/18/2023 最后编辑:Alex Rapino 更新时间:6/26/2023 访问量:89
重命名 Python 列表中的对象
rename objects in python list
问:
假设我有一个名为包含类对象的列表。我想将列表中的每个对象重命名为狗的属性,同时仍然能够修改每个索引处的对象。dogs
Dog
id
class Dog:
def __init__(self, name, age, breed, id):
self.name = name
self.age = age
self.breed = breed
self.id = id
dogs = []
intake = input("Enter the number of dogs to intake:")
for i in range(0,int(intake)):
name = input("Name of dog: ")
age = input("Age of dog: ")
breed = input("Breed of dog: ")
dog_id = input("Dog ID: ")
dogs.append(Dog(name, age, breed, dog_id))
如果打印列表中的所有对象,则会得到如下内容:
[<__main__.Dog object at 0x1234>, <__main__.Dog object at 0x5678>]
我想将列表中的所有对象重命名为狗 id,同时保留它们的属性。
答:
-1赞
X-_-FARZA_ D-_-X
6/18/2023
#1
对于这样的行为,您需要在 Dog 类上刺穿__str__方法 此外,您必须逐个打印狗或在每只狗上调用 str(dog)
class Dog:
def __init__(self, name, age, breed, id):
self.name = name
self.age = age
self.breed = breed
self.id = id
def __str__(self):
return f"{self.id}"
dogs = []
intake = 2
for i in range(0, int(intake)):
name = input("Name of dog: ")
age = input("Age of dog: ")
breed = input("Breed of dog: ")
dog_id = input("Dog ID: ")
dogs.append(Dog(name, age, breed, dog_id))
for dog in dogs:
print(dog)
print([str(dog) for dog in dogs])
评论
0赞
Alex Rapino
6/18/2023
假设我想修改一只狗,dogs = [id1,id2,id3] 我想重命名 id2 的“Fluffy”,然后我会做类似 ''' dog_to_modify = input(“狗 ID 或名称:”) dogs.index(str(dog_to_modify)) ''' 然后调用 def set_<attr>(attr)?
0赞
Leon Raj
6/18/2023
#2
如果您想使用dog_id访问数据,最好只使用嵌套字典。
intake = int(input("Enter the number of dogs to intake:"))
Dogs={}
for i in range(0,intake):
name = input("Name of dog: ")
age = int(input("Age of dog: "))
breed = input("Breed of dog: ")
dog_id = input("Dog ID: ")
Dogs[dog_id]={'name':name,'age':age,'breed':breed}
#To get a list of all the IDs, you could use Dogs.keys()
print(Dogs[<enter the dog ID here>]['name'])
您可以使用 ID 访问任何名称、品种或年龄。 (请记住,ID 应该用引号括起来,因为它是一个字符串,如果您在获取 dog_id 的输入时使用 int(),则不必这样做)
若要更改值,可以执行以下操作
Dogs[enter the dog ID here]['name' or 'age' or 'breed']= enter the new value
1赞
Tanveer Ahmad
6/26/2023
#3
@dataclass
class Dog:
name: str
age: int
breed: str
id: int = field(default_factory=lambda: Dog._get_next_id())
next_id: int = 1 # Class variable to track the next ID
def __repr__(self):
return f"MyClassDog(id={self.id}, name='{self.name}', age={self.age}, breed={self.breed})"
@classmethod
def _get_next_id(cls):
_id = cls.next_id
cls.next_id += 1
return _id
dogs = []
intake = input("Enter the number of dogs to intake:")
for i in range(0, int(intake)):
name = input("Name of dog: ")
age = int(input("Age of dog: "))
breed = input("Breed of dog: ")
dogs.append(Dog(name, age, breed))
print(dogs)
评论
Dogs
Dog
edit_name
list