Skip to content

Instantly share code, notes, and snippets.

@adamcee
Created February 17, 2024 00:36
Show Gist options
  • Save adamcee/5a3be9028a94b547b8d1bfedeb88b9c2 to your computer and use it in GitHub Desktop.
Save adamcee/5a3be9028a94b547b8d1bfedeb88b9c2 to your computer and use it in GitHub Desktop.
Aviary OOP example
class Aviary:
def __init__(self, name, birds=[]):
self.birds = birds
self.name = name
def add_bird(self, bird):
self.birds.append(bird)
class Bird:
aviary = Aviary("a1")
def __init__(self, name):
self.name = name
Bird.aviary.add_bird(self)
def __repr__(self):
return f"{self.name}"
my_aviary = Aviary(name = "my_aviary")
tweety = Bird("tweety")
fido = Bird("iago")
your_aviary = Aviary("your_aviary")
your_aviary.add_bird("Hello")
fido.aviary.add_bird("Bye")
my_aviary.name = "test"
fido.aviary.name = "fi"
#all 3 print [tweety, iago, 'Hello', 'Bye']
print(my_aviary.birds)
print(fido.aviary.birds)
print(your_aviary.birds)
#all 3 have different addresses
print(my_aviary)
print(fido.aviary)
print(your_aviary)
print(id(my_aviary))
print(id(fido.aviary))
print(id(your_aviary))
#my_aviary, your_aviary have different names. fido and tweety share the same name
print(my_aviary.name)
print(your_aviary.name)
print(fido.aviary.name)
print(tweety.aviary.name)
@adamcee
Copy link
Author

adamcee commented Feb 17, 2024

Because Bird.aviary is a class attribute, and, because when Python reads the Bird class definition and creates our "Bird" class, it creates a new aviary (named "a1") that is assigned to Bird.aviary, every time we create a new bird it gets added to that aviary.

fido.aviary is unrelated to whether we do some_aviary.add_bird(fido) b/c fido.aviary is the Bird class attribute aviary.

I think I mixed up multiple examples in this code as it doesnt make a lot of sense to have a Bird.aviary class attribute and have the Aviary have an Aviary.add_bird() method since as you pointed out it means weirdly we can add birds to a bunch of aviaries but they all simultaneously also belong to Bird.aviary .

This is probably from explaining/demo'ing multiple things during the lesson.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment