阅读量:0
在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
对象的属性。