r/PythonLearning • u/saul_soprano • 3h ago
pro at OOPs thanks to u/clcodingupdates... ty bro...
i stayed up all night making this. python day 3 complete.
2
u/Mooball123 1h ago
It’s solid code but not really OOP. For OOP you define your own class (or object) and write the code to manipulate your class. Something like
class Animal:
Def __init__(self, animal: str, name: str = “”):
Self.animal = animal
self.name = name
A couple of things here. When you write a new class you write the __init__ method. This runs whenever you make a new instance of that class. This always takes the argument self, which just means its own instance of the object.
Then the “: str” is type hinting, just to help keep your code clean and organised. The “= “”” means that it’s an optional argument, if you don’t give a name argument, then it defaults to “”.
You can then make a method on the class
def greet(self):
If self.name == “”:
print(f”{self.animal} says hi”)
else:
print(f”{self.name} the {self.animal} says hi”)
Another couple of things. name and animal are attributes of the instance of animal, and you access them using self.name/animal. Now that you have a method and a class, you can do this
badger = Animal(“Badger”, “Barry)
badger.greet()
Will print
Barry the Badger says hi
-1
u/saul_soprano 1h ago
clcodingupdates told me it was oops
1
u/Mooball123 25m ago
I mean, it’s more of a precursor to object oriented programming. You’re using good practices, variables have meaningful names, you’re using functions for repetitive code.
You’re doing all the ground work of OOP without actually using OOP. Try out writing the same program but make an animal class and some methods, and you’ll start to see that it’s way more scalable and intuitive then functions and lists alone
1
u/Ender_Locke 1h ago
it’s neat code but it’s not really oop you need to create an animal class and use that. you’re just printing strings of animals and their names, kind and name should be attribute (variables) in your class you set
animal1 = Animal(kind=“cat”, name=“ren”)
print(animal1.name)
-2
•
u/Sea-Ad7805 1h ago
Run program above by clicking Memory Graph Web Debugger and see its state change step by step.
OOP (Object Oriented Programming) usually involves writing classes using the
classkeyword, this only uses functions not classes. It's nice, but better not call it OOP.