Python is an object oriented language. This basically means that we can create classes and objects for our data.
Classes serve as the blueprint for our objects. They can be used to create as many objects as you want that follow that specific blueprint.
Using that blueprint, we can potentially build any of the following houses on the right!
class Person:
"This is a person class"
age = 10
def greet(self):
print('Hello')
def printAge(self):
print(age)
# create a new object of Person class
harry = Person()
print(Person.greet)
# Output: <function Person.greet>
print(harry.greet)
# Output: <bound method Person.greet of <__main__.Person object>>
harry.greet()
# Output: Hello
To create a class, use the class keyword followed by the class name. Within the class, you can store variables and functions, called methods, that can be called on the object. Each object of the class that is created will contain all of the associated variables and methods.
To call a method of an object, use the dot (.) operator. For example, to call the greet method on the object harry, you would write: harry.greet()
Make sure to name your classes with names that are reflective of the data it stores and the intended functionality. It should be clear what kind of class it is.
For example, naming a class ClassOne does not tell the user what the purpose of this class is or what kind of data it stores.
Also make sure to follow naming conventions, such as camelCase or snake_case.
It is a good practice to declare your classes as a separate Python file, then import them into your main file. That way you can use that same class in other projects and scripts.
Make sure you declare a class in the same directory you want to use it.