Day 20: Accessing Python Class Object Attributes
Understanding the 'self' Keyword in Python Classes
In Python classes, the 'self' keyword is used to access the attributes and methods of an object from within the object's class. It refers to the instance of the class and is used to distinguish the instance's attributes and methods from those of the class itself.
To access the attributes of an object from within the class, use the 'self' keyword followed by the attribute name. Similarly, to access the methods of an object from within the class, use the 'self' keyword followed by the method name.
Accessing Attributes and Methods with 'self' in Python Classes
class Dog:
def __init__(self, name, breed):
self.name = name
self.breed = breed
def bark(self):
print("Woof!")
def show_info(self):
# Accessing attributes with 'self'
print(f"Name: {self.name} Breed: {self.breed}")
dog = Dog("Fido", "Labrador")
dog.show_info()
# Output: "Name: Fido Breed: Labrador"
In the above example, the 'show_info' method uses the 'self' keyword to access the 'name' and 'breed' attributes of the 'Dog' instance.
Using 'self' to Access Methods in Python Classes
class Dog:
def __init__(self, name, breed):
self.name = name
self.breed = breed
def bark(self):
print("Woof!")
def show_info(self):
print(f"Name: {self.name} Breed: {self.breed}")
def do_bark(self):
# Accessing method with 'self'
self.bark()
print("Barking!")
dog = Dog("Buddy", "Poodle")
dog.do_bark() # Output: "Woof! Barking!"
In this example, the 'do_bark' method uses the 'self' keyword to call the 'bark' method of the 'Dog' instance.
Learn More
Want to learn more about Python for Machine Learning? Check out the full course HERE.
Need help mastering Machine Learning?
Don't just follow along — join me! Get exclusive access to me, your instructor, who can help answer any of your questions. Additionally, get access to a private learning group where you can learn together and support each other on your AI journey.