YouTip LogoYouTip

Python Person Class

## Python OOP: Creating a Person Class with Name and Age Attributes Object-Oriented Programming (OOP) is a fundamental paradigm in Python. It allows you to model real-world entities as software objects containing data (attributes) and behaviors (methods). In this tutorial, we will walk through creating a simple yet foundational `Person` class in Python. This class will contain two attributesβ€”`name` and `age`β€”and a method to display this information. --- ## Syntax and Core Concepts Before diving into the code, let's understand the key components used to build a class in Python: * **`class` Keyword**: Used to define a new user-defined type. * **`__init__` Method**: The constructor method in Python. It automatically runs when you instantiate (create) a new object from the class. It is used to initialize the object's attributes. * **`self` Parameter**: Represents the specific instance of the class you are currently creating or manipulating. It allows you to access the attributes and methods associated with that individual object. * **Attributes**: Variables bound to the class instance (e.g., `self.name` and `self.age`). * **Methods**: Functions defined inside a class that describe the behaviors the object can perform. --- ## Code Example Below is a complete, runnable example demonstrating how to define the `Person` class, instantiate an object, and call its method. ```python class Person: def __init__(self, name, age): # Initialize the instance attributes self.name = name self.age = age def display_info(self): # Method to print the person's details print(f"Name: {self.name}, Age: {self.age}") # Create an instance of the Person class person = Person("Alice", 30) # Call the method to display the object's information person.display_info() ``` ### Output ```text Name: Alice, Age: 30 ``` --- ## Step-by-Step Code Explanation 1. **`class Person:`** This line defines a new class named `Person`. By convention, class names in Python use CamelCase. 2. **`def __init__(self, name, age):`** This is the constructor. When we write `Person("Alice", 30)`, Python internally calls this method, passing `"Alice"` to `name` and `30` to `age`. 3. **`self.name = name` and `self.age = age`** These lines assign the values passed during instantiation to the object's local properties (attributes). Using `self` ensures that these variables belong to the specific instance being created. 4. **`def display_info(self):`** This defines an instance method. It takes `self` as its first argument so it can access the instance's attributes (`self.name` and `self.age`) using an f-string. 5. **`person = Person("Alice", 30)`** This instantiates a new `Person` object. The variable `person` now holds a reference to this unique object. 6. **`person.display_info()`** This calls the `display_info` method on our `person` instance, which outputs the formatted string to the console. --- ## Key Considerations & Best Practices * **Type Hinting (Optional but Recommended):** For larger projects, you can use Python's type hinting to make your code more readable and robust: ```python class Person: def __init__(self, name: str, age: int) -> None: self.name: str = name self.age: int = age ``` * **The `__str__` Method:** If you want a clean string representation of your object when calling `print(person)`, consider overriding the built-in `__str__` method instead of or in addition to custom display methods: ```python def __str__(self): return f"Person(Name: {self.name}, Age: {self.age})" ``` * **Encapsulation:** In Python, all attributes are public by default. If you want to signal that an attribute is private and should not be accessed directly from outside the class, prefix it with a single underscore (e.g., `self._age`).
← Python Stack ClassPython Palindrome String β†’