Google News
logo
Python Program to Create a Class
To create a class in Python, you can use the `class` keyword followed by the name of the class. Here is an example :
class MyClass:
    x = 5​

In the example above, we define a class named `MyClass`. The class has a single attribute `x` with a value of 5.

To create an object of the class, you simply call the class like a function :

obj = MyClass()


Now, the variable `obj` holds an object of the `MyClass` class. You can access the attributes of the object using the dot notation:

print(obj.x)  # Output: 5
You can also define methods inside a class using the `def` keyword:
class MyClass:
    x = 5
    
    def hello(self):
        print("Hello, world!")​
In the example above, we define a method named `hello` that simply prints "Hello, world!" to the console. To call this method on an object, you use the dot notation :
obj = MyClass()
obj.hello()​ # Output: Hello, world!
The `self` parameter in the method definition refers to the object that the method is called on.