create a class called person in python

To create a class called Person in Python, we can follow the syntax:

main.py
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    def get_name(self):
        return self.name
    
    def get_age(self):
        return self.age
203 chars
11 lines

In the above code, __init__ is the constructor method, which is executed when an object of the class is created. self is used to represent the instance of the class.

We have defined two methods get_name and get_age, which are used to retrieve the values of the name and age attributes.

We can create an instance of the Person class by calling the constructor with the required arguments:

main.py
person1 = Person("John", 25)
29 chars
2 lines

The above code creates an instance of the Person class with name "John" and age 25. We can then access the attributes of this instance using the methods we defined:

main.py
print(person1.get_name())  # Output: "John"

print(person1.get_age())   # Output: 25
85 chars
4 lines

gistlibby LogSnag