Title here
Summary here
In Python, we use classes to define similar data structures as structs in other languages. Here’s an example to illustrate the concept.
class Person:
def __init__(self, name, age=0):
self.name = name
self.age = age
def new_person(name):
p = Person(name)
p.age = 42
return p
def main():
print(Person("Bob", 20))
print(Person(name="Alice", age=30))
print(Person(name="Fred"))
print(Person(name="Ann", age=40))
print(new_person("Jon"))
s = Person(name="Sean", age=50)
print(s.name)
sp = s
print(sp.age)
sp.age = 51
print(sp.age)
dog = {"name": "Rex", "is_good": True}
print(dog)
if __name__ == "__main__":
main()__init__ method acts as the constructor.new_person function creates a new Person instance and sets an age default.To run the program, save it to a file, for example, structs.py, and execute it with Python.
$ python structs.py
<__main__.Person object at 0x7f8301731c70>
<__main__.Person object at 0x7f8301731dc0>
<__main__.Person object at 0x7f8301731d30>
<__main__.Person object at 0x7f8301731df0>
<__main__.Person object at 0x7f8301731e50>
Sean
50
51
{'name': 'Rex', 'is_good': True}Python does not display the content of objects directly, so to make it more readable, you could define a __str__ method in the Person class:
class Person:
def __init__(self, name, age=0):
self.name = name
self.age = age
def __str__(self):
return f"Person(name={self.name}, age={self.age})"With this change, the output will be more readable.
$ python structs.py
Person(name=Bob, age=20)
Person(name=Alice, age=30)
Person(name=Fred, age=0)
Person(name=Ann, age=40)
Person(name=Jon, age=42)
Sean
50
51
{'name': 'Rex', 'is_good': True}Next example: Methods.
Comments powered by Disqus