在Python中,有以下幾種方法可以定義對象數組:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
person1 = Person("John", 25)
person2 = Person("Alice", 30)
persons = [person1, person2]
import numpy as np
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
point1 = Point(2, 3)
point2 = Point(4, 5)
points = np.array([point1, point2])
import pandas as pd
class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model
car1 = Car("Toyota", "Camry")
car2 = Car("Honda", "Accord")
cars = pd.Series([car1, car2])
需要注意的是,以上的方法只是將對象保存在數組中,并不是真正的對象數組。在Python中,列表和數組是動態的,可以存儲不同類型的元素。如果需要在靜態類型語言中定義真正的對象數組,可以使用第三方庫,如NumPy或Pandas。