I'm new to python (and coding in general) and I've been really struggling to wrap my head around classes. I feel like the concept of a class is just starting to click for me, but adding sub-classes (is that the same thing as a meta-class???) into the mix has confused me even more.
I've been trying to work my way through the python zoo project, by my friend's recommendation. The goal is to use classes and object oriented programming to create a program that can represent zoos which have cages, which have animals inside, and those animals have unique attributes. (here is the exercise if you want to look at it, but I'll provide the code relevant to my confusion https://github.com/gabits/zoo_exercise)
class Animal:
""" Can be placed inside cages, and according to its place in food chain
it has a list attribute of its prey (what it likes to eat).
"""
prey = []
def __init__(self):
self.name = 'Unnamed' # Default naming, to be modified
def __repr__(self):
""" Identifies the Animal by its name and species (subclass).
"""
species = self.__class__.__name__
return self.name + " " + species if self.name != 'Unnamed' else species
class Mouse(Animal):
def __init__(self):
super().__init__()
class Goat(Animal):
def __init__(self):
super().__init__()
My current understanding of this code:
- We have the class Animal that gives the name 'unnamed' to each animal
- The mouse and Goat classes are sub-classes of Animal
What I don't understand:
- what
__repr__
,__class__
, and__name__
each do - why do things dealing with classes all have the underscores before and after the variable? Does python treat these objects differently? or is the underscore just a naming scheme that signals something?
- what the
__repr__(self)
function is doing
Any help is appreciated!