怎样在Python中嵌套结构体

avatar
作者
猴君
阅读量: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) 

在上面的示例中,我们创建了两个类AddressPersonPerson类中包含一个Address对象作为其属性。我们可以通过访问Person对象的属性来访问嵌套的Address对象的属性。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!