如何在Python类中创建对象列表
我们可以通过将类实例附加到 list 来在Python中创建对象列表。这样,列表中的每个索引都可以指向类的实例属性和方法,并且可以访问它们。如果您仔细观察,对象列表的行为就像 C 中的结构数组。让我们尝试借助示例更好地理解它。
示例 #1:
# Python3 code here creating class
class geeks:
def __init__(self, name, roll):
self.name = name
self.roll = roll
# creating list
list = []
# appending instances to list
list.append( geeks('Akash', 2) )
list.append( geeks('Deependra', 40) )
list.append( geeks('Reaper', 44) )
for obj in list:
print( obj.name, obj.roll, sep =' ' )
# We can also access instances attributes
# as list[0].name, list[0].roll and so on.
输出:
Akash 2
Deependra 40
Reaper 44
示例 #2:
# Python3 code here for creating class
class geeks:
def __init__(self, x, y):
self.x = x
self.y = y
def Sum(self):
print( self.x + self.y )
# creating list
list = []
# appending instances to list
list.append( geeks(2, 3) )
list.append( geeks(12, 13) )
list.append( geeks(22, 33) )
for obj in list:
# calling method
obj.Sum()
# We can also access instances method
# as list[0].Sum() , list[1].Sum() and so on.
输出:
5
25
55