Loading search index…
No recent searches
No results for "Query here"
Python’s classes and objects are used to create structured data types similar to structs. They are useful for grouping data together to form records.
class Person: def __init__(self, name, age): self.name = name self.age = age def new_person(name): p = Person(name, 42) return p if __name__ == "__main__": # This syntax creates a new instance of the class. print(Person("Bob", 20)) # You can name the fields when initializing a class. print(Person(name="Alice", age=30)) # Omitted fields will be set to the defaults defined in the `__init__` method. print(Person(name="Fred", age=0)) # Getting a reference to the object print(f"&{Person(name='Ann', age=40)}") # It’s idiomatic to encapsulate new class creation in functions print(new_person("Jon")) # Access class fields with a dot. s = Person(name="Sean", age=50) print(s.name) # You can also use dots with object instances. sp = s print(sp.age) # Objects are mutable. sp.age = 51 print(sp.age) # If a class type is only used for a single value, we can use an anonymous class. Dog = type("Dog", (object,), {"name": "Rex", "isGood": True}) dog = Dog() print(dog)
When running the Python code, the expected output is similar to:
<__main__.Person object at 0x7f3e784708e0> <__main__.Person object at 0x7f3e78470e80> <__main__.Person object at 0x7f3e78470df0> &<__main__.Person object at 0x7f3e78470e50> <__main__.Person object at 0x7f3e78470ca0> Sean 50 51 <__main__.main.<locals>.Dog object at 0x7f3e78470fd0>
Next example: Methods.