Python class and object

A class is a blueprint for creating objects in Python. It defines the attributes (variables) and methods (functions) that the objects of that class will have.

Simple example class called People:

1class People(): 2 3 def hello(self): 4 print("HELLO")

Create an object

1c = People()

Access class method

1c.hello() # Output: HELLO

Attributes and methods

Here is an example of a class called Person:

1class Person: 2 def __init__(self, name, age): 3 = name 4 self.age = age 5 6 def say_hello(self): 7 print("Hello, my name is " +

This class has two attributes, name and age, which are set in the constructor method __init__. It also has a method say_hello that prints a greeting message.

Create an object, pass value to constructor

To create an object of the class, you can call the class name followed by parentheses:

1person = Person("William", 30)

Access the attribute

You can access the attributes of the class using the dot notation:

1print( # Output: William 2print(person.age) # Output: 30

You can also call the methods of the class using the dot notation:

1person.say_hello() # Output: Hello, my name is William