python

怎样在Python中嵌套结构体

小樊
109
2024-06-15 17:02:47
栏目: 编程语言

在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对象的属性。

0
看了该问题的人还看了