__init__ of class
def __init__(self, name, sneaky=True, **kwargs):
self.name = name
self.sneaky = sneaky
for key, value in kwargs.item():
setatter(self, key, value)
def pickpocket(self):
if self.sneaky:
return bool(random.randint(0,1))
return False
def hide(self, light_level):
return self.sneaky and light_level < 10
__init__
Constructor or initiator of instance.
**kwargs
A dictionary filled with key-value pairs.
setatter
A method that allows us to assign new attributes to the instance making use of kwargs.
__init__ of superclass
We need a way to make use of the code that lives in our classes’ superclasses.
Make use of the super()
method to set the attribute values of the superclass.
import random
class Character:
def __init__(self, name, **kwargs):
self.name = name
for key, value in kwargs.items():
setattr(self, key, value)
class Thief(Character):
sneaky = True
def __init__(self, name, sneaky=True, **kwargs):
super().__init__(name, **kwargs)
self.sneaky = sneaky
def pickpocket(self):
return self.sneaky and bool(random.randint(0,1))
def hide(self, light_level):
return self.sneaky and light_level < 10