how to create a class in python

To create a class in Python, you can use the class keyword followed by the name of the class. The first method defined within the class is usually the __init__ method, which is the constructor for the class. Here's an example of a simple class in Python:

main.py
class MyClass:
    def __init__(self, name):
        self.name = name

    def print_name(self):
        print("Name:", self.name)
131 chars
7 lines

In the example above, MyClass is defined with an __init__ method that takes one argument name. It sets an instance variable self.name to the value of name. The class also has a method print_name that simply prints the name of the object.

To use this class, you can create an object of this class by calling MyClass() with the required arguments. Here's an example:

main.py
my_object = MyClass("John")
my_object.print_name()
51 chars
3 lines

This will output:

main.py
Name: John
11 chars
2 lines

gistlibby LogSnag