7 Things I Wish I Knew Earlier About Python Classes
Day 90 of experimenting with video content:
1) __init__
class Dog:
pass
dog = Dog()^ this is a legal and valid Dog object. But it has no attributes, and we cannot do much useful stuff with this object.
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
# create Dog object with name='rocky' & age=5
dog = Dog('rocky', 5)^ using __init__, we can allow our users to assign attributes to our objects eg. name and age for our Dog class. Which makes our objects a lot more useful.
2) __str__
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
dog = Dog('rocky', 5)
print(dog) # <__main__.Dog object at 0x1042dfd40>^ by default, when we print our Dog object dog, we get this gibberish.
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f'Dog(name={self.name} age={self.age})'
dog = Dog('rocky', 5)
print(dog) # Dog(name=rocky age=5)^ by defining our own __str__ method, we override the default behaviour above, and control our object’s behaviour when we do str(dog) (which is automatically done when we use print())
3) __dict__
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
dog = Dog('rocky', 5)^ a simple Dog class
dog = Dog('rocky', 5)
print(dog.__dict__) # {'name': 'rocky', 'age': 5}^ the __dict__ attribute is a dictionary containing all attributes of our object. This is useful to inspect complicated objects and classes with many many attribtues.
4) super().__init__
Let’s define 2 classes — Rectangle and Square
- Rectangle has 4 sides and 4 right angles