create nested objects in python

To create nested objects in Python, you can use dictionaries. A dictionary is a collection of key and value pairs, where the value can be another dictionary. You can nest dictionaries inside each other to create a hierarchy of information. Here's an example:

main.py
person = {
    "name": "John",
    "age": 30,
    "address": {
        "street": "123 Main St",
        "city": "Anytown",
        "state": "CA",
        "zip": "12345"
    }
}
177 chars
11 lines

In this example, we have a dictionary called person that contains three key-value pairs. The third key, address, has a dictionary as its value. This dictionary contains four key-value pairs.

To access nested values, you can use multiple square brackets. For example:

main.py
print(person["address"]["city"])  # Outputs: Anytown
53 chars
2 lines

You can also create nested objects using classes in Python, where an object can have an attribute that is another object. Here's an example:

main.py
class Address:
    def __init__(self, street, city, state, zip):
        self.street = street
        self.city = city
        self.state = state
        self.zip = zip

class Person:
    def __init__(self, name, age, address):
        self.name = name
        self.age = age
        self.address = address

john_address = Address("123 Main St", "Anytown", "CA", "12345")
john = Person("John", 30, john_address)

print(john.address.city)  # Outputs: Anytown
458 chars
18 lines

In this example, we have two classes: Address and Person. Person has an attribute called address that is an instance of the Address class. We create a new instance of Address, and pass it to the constructor of Person. We can then access the city of john's address using dot notation.

gistlibby LogSnag