Classes and Objects
Construct a Class
class Fruit:
name = "" # Member Field
# Constructor method
def __init__(self, name):
self.name = name
# Member method
def show(self):
print("Name:", self.name)
Inheritance
class Banana(Fruit):
def eat(self):
print(f"{self.name} is yummy!")
b = Banana("Blue Java Banana")
# inherited method: show
b.show() # Name: Blue Java Banana
# subclass's own method: eat
b.eat() # Blue Java Banana is yummy!
Overriding
class Apple(Fruit):
nutrition = [1, 2, 3]
def show(self):
print("Name:", self.name, "Nutrition Facts:", self.nutrition)
a = Apple("Big Apple")
# overrided method
a.show() # Name: Big Apple Nutrition Facts: [1, 2, 3]
Getters and Setters with @property
Python provides a built-in @property
decorator which eases the use of getters and setters in classes.
class RoomTemperature:
def __init__(self, temperature=0):
self.__temperature = temperature
@property
def celsius(self):
return self.__temperature
@celsius.setter
def celsius(self, value):
if value < -273.15:
raise ValueError("impossible temperature")
self.__temperature = value
@property
def fahrenheit(self):
return self.__temperature * 9 / 5 + 32
rt = RoomTemperature(25)
# with the help of @property decorator, method access is as simple as field access
print(rt.celsius) # 25
print(rt.fahrenheit) # 77.0
rt.celsius = 500 # OK
rt.celsius = -500 # ValueError: impossible temperature
Class Methods
Class Method is a method that gets passed the class it was called on, or the class of the instance it was called on, as first argument. This is useful when you want the method to be a factory for the class.
class Fruit:
def foo(self, x):
print(f"executing foo {self}, {x}")
@classmethod
def class_foo(cls, x):
print(f"executing class_foo {cls}, {x}")
f = Fruit()
f.foo(42) # executing foo <__main__.Fruit object at 0xf5add8>, 42
f.class_foo(42) # executing class_foo <class '__main__.Fruit'>, 42
Fruit.class_foo(42) # executing class_foo <class '__main__.Fruit'>, 42
Static Methods
Static methods are a way to define methods within a class that logically belong to the class. It knows nothing about the class or instance it was called on. It just gets the arguments that were passed, no implicit first argument.
class TemperatureUtil:
@staticmethod
def celsius_to_fahrenheit(celsisu):
return celsisu * 9 / 5 + 32
print(TemperatureUtil.celsius_to_fahrenheit(25)) # 77.0
Magic Methods
__str__ method defines a custom string representation of the class.
__str__
class Fruit:
def __init__(self, name):
self.__name = name
print(Fruit("banana")) # <__main__.Fruit object at 0xc24fd8>
# with __str__ method
class Fruit:
def __init__(self, name):
self.__name = name
def __str__(self):
return f"Name: {self.__name}"
print(Fruit("banana")) # Name: banana
__del__ method is referred to as a destructor method. It is called after an object's garbage collection occurs.
__del__
class Fruit:
def __del__(self):
print("I'm gone!")
f = Fruit()
del f # I'm gone!
Code Challenge
Try to modify the code provided in the editor to make a class instance which represents itself as
Tom(22) Skills: C++,Python,JavaScript
.