在Python中,可以通過創建類來實現嵌套結構體的功能。以下是一個示例:
class Address:
def __init__(self, street, city, state, zipcode):
self.street = street
self.city = city
self.state = state
self.zipcode = zipcode
class Person:
def __init__(self, name, age, address):
self.name = name
self.age = age
self.address = address
# 創建地址對象
address = Address("123 Main St", "Cityville", "CA", "12345")
# 創建人員對象并將地址對象嵌套在其中
person = Person("John Doe", 30, address)
# 訪問嵌套結構體的屬性
print(person.name)
print(person.address.street)
print(person.address.city)
print(person.address.state)
print(person.address.zipcode)
在上面的示例中,我們創建了兩個類Address
和Person
,Person
類中包含一個Address
對象作為其屬性。我們可以通過訪問Person
對象的屬性來訪問嵌套的Address
對象的屬性。