create a class in python

To create a class in python, we use the class keyword followed by the name of the class. The class can have attributes and methods defined inside it.

Here is an example of creating a simple Person class with a name attribute and a greet() method:

main.py
class Person:
    def __init__(self, name):
        self.name = name
    
    def greet(self):
        print(f"Hello, my name is {self.name}. Nice to meet you!")
162 chars
7 lines

In this example, __init__ is a special method in python classes that is called when an object of the class is created. It takes a self parameter that refers to the object being created, and any additional parameters that the class needs. In this case, we're passing in a name parameter and assigning it as an attribute of the object using self.name.

The greet() method takes a self parameter as well and simply prints out a greeting message using the name attribute of the object.

To use this class and create objects from it:

main.py
p1 = Person("Alice")
p2 = Person("Bob")

p1.greet()   # Output: "Hello, my name is Alice. Nice to meet you!"
p2.greet()   # Output: "Hello, my name is Bob. Nice to meet you!"
175 chars
6 lines

Here, we're creating two objects p1 and p2 from the Person class with different name attributes. We can then call the greet() method on each object to print out a greeting message using the object's name attribute.

gistlibby LogSnag