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.py162 chars7 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.py175 chars6 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