Person’s Private Details

Implement a class named Person with private attributes name and age. Write a method to display these attributes and make sure the attributes are accessible only within the class.

Example 1:

person = Person("Alice", 30)
print(person.display())

Output: "Name: Alice, Age: 30"

Example 2:

person = Person("Bob", 22)
print(person.display())




Output: "Name: Bob, Age: 22"

Utilize Python’s naming convention for private attributes (preceding with an underscore) and create a public method to access them.

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

    def display(self):
        return f"Name: {self._name}, Age: {self._age}"

# Test the class
person = Person("Alice", 30)
print(person.display())  # Output: "Name: Alice, Age: 30"

© Let’s Data Science

LOGIN

Unlock AI & Data Science treasures. Log in!