Classes in Python allow for **object-oriented programming.** OOP is a broader coding paradigm that many software developers adopt and use to inform the design of their programs.
Classes are the blueprints for creating objects. Classes define all the attributes/properties and functionality that objects should contain.
Objects are the instances utilized within our program.
Consider food and cooking. We could have a vegetable class, which has particular attributes, such as as color, weight, and so on. Then, we could create specific objects of the vegetable class, such as carrots, potatoes, corn, and so on.
class Food: # Pascal naming convention
def consume(self): #define Class Methods
print("Consuming food object")
food = Food() # create new instance of Point class
print(type(food)) # <class '__main__.Food'>
print(isinstance(food, int)) # False
The above defines a new class Point which contains a single method called draw, which prints out the word draw. We can then create an instance of Point, which establishes our object that can be consumed or utilized in our code.
class Food: # Pascal naming convention
def __init__(self, weight, category):
self.weight = weight
self.category = category
def consume(self):
print(f"Consuming Food: ({self.category})")
food = Food(1.5, 'Vegetable') # create new Food object
food.consume()
Attributes are class-specific variables. We use attributes to define all the properties that are specific to the type of class we are defining.
class Food: # Pascal naming convention
edible = True # class attribute
def __init__(self, weight, category):
self.weight = weight # instance attribute
self.category = category
def consume(self):
print(f"Consuming Food: ({self.category})")
food = Food(1.5, 'Vegetable') # create new Food object
food.edible # True, access class attribute from object
Food.edible # True, access class attributes from class
Class Attributes are global properties that apply to all members of a particular class. They can be accessed directly from an object instance or from the Class itself. In general. they are not utilized as much as
Instance Attributes r
Methods are functions specific to a particular class, and just like
Class Methods
Instance Methods