Created
February 17, 2024 00:36
-
-
Save adamcee/5a3be9028a94b547b8d1bfedeb88b9c2 to your computer and use it in GitHub Desktop.
Aviary OOP example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 toBird.aviary
, every time we create a new bird it gets added to that aviary.fido.aviary
is unrelated to whether we dosome_aviary.add_bird(fido)
b/cfido.aviary
is the Bird class attributeaviary
.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 anAviary.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 toBird.aviary
.This is probably from explaining/demo'ing multiple things during the lesson.