Python classes and objects¶
In Python, classes and objects are used to group related variables into a single unit.^[400-devops__09-Scripting-Language__python__introduction__README.md] This is useful when managing data entities that have multiple properties, such as a customer with a first name, last name, and ID, rather than storing them as simple strings.^[400-devops__09-Scripting-Language__python__introduction__README.md]
Classes¶
A class serves as a blueprint for creating data structures.^[400-devops__09-Scripting-Language__python__introduction__README.md] It defines the attributes (variables) and methods (functions) that the instantiated objects will possess.^[400-devops__09-Scripting-Language__python__introduction__README.md]
Methods¶
Methods are functions defined within a class that operate on the object's data.^[400-devops__09-Scripting-Language__python__introduction__README.md] For example, a fullName() method within a Customer class can concatenate the firstName and lastName attributes.^[400-devops__09-Scripting-Language__python__introduction__README.md]
The Constructor¶
The __init__ method is a special method known as the constructor.^[400-devops__09-Scripting-Language__python__introduction__README.md] It allows new objects to be initialized with specific values immediately upon creation, rather than setting each attribute individually after the object is created.^[400-devops__09-Scripting-Language__python__introduction__README.md]
Objects¶
An object is an instance of a class.^[400-devops__09-Scripting-Language__python__introduction__README.md] Once an object is created (instantiated), it contains the actual data defined by the class structure.^[400-devops__09-Scripting-Language__python__introduction__README.md] You can access the object's data and methods using dot notation (e.g., object.attribute).^[400-devops__09-Scripting-Language__python__introduction__README.md]
Example Usage¶
The following example demonstrates defining a class with a constructor and a method, creating an instance of it, and using the method:
class Customer:
def __init__(self, c="", f="", l=""):
self.customerID = c
self.firstName = f
self.lastName = l
def fullName(self):
return self.firstName + " " + self.lastName
# Creating an object (instance)
marcel = Customer("h", "Marcel", "Dempers")
# Accessing functionality
print(marcel.fullName())
^[400-devops__09-Scripting-Language__python__introduction__README.md]
Related Concepts¶
- [[Functions]]
- [[Dictionaries]]
- [[Object-oriented programming]]
Sources¶
- 400-devops__09-Scripting-Language__python__introduction__README.md