class definition in python

To define a class in Python, you use the class keyword followed by the name of the class. Here's an example of a simple class definition:

main.py
class MyClass:
    pass
24 chars
3 lines

This class doesn't do anything yet, but it provides a framework for defining methods and properties. Here's an example of a class with a method:

main.py
class Person:
    def __init__(self, name):
        self.name = name
        
    def say_hello(self):
        print(f"Hello, my name is {self.name}.")
152 chars
7 lines

In this example, the Person class has an __init__ method that initializes a name property. It also has a say_hello method that prints a greeting using the name property.

To instantiate an object from this class, you use the class name followed by parentheses:

main.py
person = Person("Alice")
person.say_hello() # output: Hello, my name is Alice.
79 chars
3 lines

This creates a Person object with the name property set to "Alice", and then calls the say_hello method to print a greeting.

gistlibby LogSnag