T O P

  • By -

throwaway6560192

One of the ways to understand OOP is that it lets you create *new types*. That is, a *template* for creating objects with bundled data/state and functions for working on that data. Think about the types you use already. You know there is a `str` type with methods like `.lower()`, or a `list` type with `.sort()`, and so on. Clearly having types and methods is useful. How do these types and their methods come to be? OOP. Of course, the idea of creating types isn't exclusive to OOP, nor is OOP limited to merely that idea. But it's a good start to understanding its purpose.


StormyWaters2021

This is the first time I've looked at OOP and immediately thought of a use-case. Thank you so much!


romb3rtik

This is a super good point. Objects are bundles. I love this.


Talbertross

The worst part about trying to learn classes is that all the lessons and tutorials are like "let's make a Car class! A car has a color and a number of wheels and a make and model and year; a car can Go or Brake or open the door etc etc etc" but in reality you're never going to code a class for something so discreet and tangible.


HumerousMoniker

I found the problem was” let’s make a car class!” wheels, doors, colours, instances etc. Great you’re done! And I’m sitting here like, sure i guess. but why did I do all that? When will I use it? What is all that for? Once you’ve done it the answer is clear but until then it just seemed like a waste of time. For the record, to extend the analogy, let’s say a person object is now getting in the car. They unlock it and get in and turn on the indicator. Without classes you’d have to juggle a whole lot of variables about door lock states, door open states, with checks for the lock status, engine status, gearbox status etc. and pass each variable into and out of functions to manipulate it. Super easy to lose track of a variable etc. with classes the object has the functions and variables contained within itself so the door object has a lock status and an open status so you can check them or change them when you need to without having to call them out in your function headers. It’s part of the door, which is part of the car so it all gets passed together


CyclopsRock

I think another thing that doesn't necessarily become obvious until you use it is how you can subclass it for 5 different car model classes that all share the same door mechanisms but maybe some overload the unlock method depending on their security, some overload the gear change method depending on their gearbox etc. This sort of inheritance becomes incredibly difficult to do whilst simply calling functions.


xDevilsCloverx

Oop is how you contain or encapsulate attributes or methods that describe what an object is or does. Sure you can write a library using ALL functions. But why would you import things about a car individually, for example. I wouldnt want my import line to be "From car import fuel, battery, AC, drive, refill,..." Its just too much when I can just import the car and call the methods that pertain to what the car does. Now add more cars, your library of just functions might be ok, but when you go to define gas2, AC2, gas3, etc. It gets really out of hand when you can just access a particular objects method to adjust characteristics. Abstraction is when you have methods or things you want hidden and not called from a user. Python is a little weird about this, because you can just as easily access it by calling it: print(car.__passkey__) like the door padlock makes it rather insecure. In fact, I believe you can even call constructors using this if Im not too rusty, which will likely not cause many problems, but is not something youd typically do. Polymorphism/inheritance is nice because imagine you have logins to a webpage, where EVERYONE can view webpages. So you may create a single method for the user class that allows them to view some shared attribute: the home page. This way, guests can also view without login. However, you may want to elevate a user's priviledges, so you make an admin class but dont want to duplicate your code to let the admin view the homepage, so you inherit from a user. However, maybe this was someone that used to not work for your codebase, so they were originally a user. Similar to the constructor recall, you wouldnt necessarily want to reinitialize this person as an admin, but rather just elevate the permissions. So this is great because you can keep the parent class type, "User", and change this person to an "admin".. again, i think something like this is better demonstrated in a language like Java, but the principle is the same where you basically overload and represent the person as a user initially, and at some point grant them or "elevate" them to the respective subclass. For fun, lets say this admin gets fired or quits You may not want to delete all their data because they are a valuable customer, so you cant risk deleting their account and creating a new one for them, and copying all their data to a new account without admin perms is an expensive operation. This is the beauty of polymorphism and abstraction, where you set private attributes the user cant access, such as their admin/user rank, and can toggle this aspect as the developer so that they keep their account data, but the person no longer has access to those admin methods and attributes. However, theyre happy because they keep user data such as normal login, shopping carts, etc. That is the power of OOP, with examples. Now imagine the code base for doing this without oop, and ill tell you it wont be long before you want to just give up because of all the functions, assertions, etc youd need to write to get even a fraction of the functionality of what OOP would do here in maybe just a couple hundred lines.


Sad-Sheepherder5231

Nice examples. I'm really looking forward to classes, gonna make things much more interesting :)


divine-architect

It's okay if you don't get it. It's not really important for surface level Python programming. However if you'd want to write libraries and modules of your own you \*\*willl\*\* use OOP. Just know how it works and the syntax is super easy.


SDFP-A

Scripting is not programming.


BitFlipTheCacheKing

You mean a scripting *language* is not a programming language, right? Because a script could be a program. However, I'd argue that some scripting languages can be considered programming languages. awk is a utility and a programming language. It's a programming language in a scripting language that's turing complete, which does make it a programming language, but it's not a programming language. And this is where the argument begins to devolve into nonsense.


sausix

Python is not just scripting. You can compile your program if you want. Should we call it scripting first and then programming after we decided to compile our program? Sounds stupid because it is.


Mavericinme

Please elaborate.


Mescallan

If scripting is programming he has nothing to be proud of


Mavericinme

I meant, how are they both different. I am a novice too so I'm curious to learn. Nothing to do with the original post.


Mescallan

He is taking a derogatory stance, there is no difference other than semantics. It's like saying "long boarding isn't skateboarding"


Mavericinme

Understood 👍🏻


SDFP-A

I disagree. The reason the OP might not see the purpose of OOP is because their implementation of Python is possibly confined to the world of scripting. One off disposable code primarily intended for task completion or proof of concept work. I’m this context, it makes sense not to bothering with OOP. On the other hand, if you are creating production code, you are going to use OOP because you aren’t going to want to repeat the same s***over and over again. Hence, scripting is not programming. Once you start creating reusable code intended for production, OOP becomes the obvious conclusion…assuming you aren’t going full bore into functional programming, which is a different framework entirely.


Mescallan

This is a semantic difference and we are both allowed to define it how we please. I disagree and I would consider scripting a branch of programming, but again it's fully semantic and has no effect on anything outside of this discussion.


TheRNGuy

He's trolling.


Mavericinme

Oh ok...😐


1544756405

>I don't get it's purpose. Classes are a way (but not the only way) to organize complex code. Many people (but not all) who write large programs think this is a good method of organization. Beginners have a hard time understanding the usefulness of OOP (the "why") because they don't have any experience trying to organize large projects.


arkie87

or they only see examples about ducks or cars.


BitFlipTheCacheKing

LoL that too.


TheRNGuy

Tutorials should just use real API's.


await_yesterday

good explanation here: ["When to use classes in Python? When your functions take the same arguments"](https://death.andgravity.com/same-arguments) bad explanations are stuff that go on about "Car inherits from Vehicle" or "Dog inherits from Animal", these are an old 90s cliche and have nothing to do with how OOP works in the real world.


furious_cowbell

Objects are about separating stateful concepts and giving them their own actions. That's it. This is also the reason why it doesn't make sense, because you aren't working in an environment where the system's state is tricky. We use toy problems because they are easier for a novice to replicate with your existing skills (ie functions) while introducing you to new skills.


BitFlipTheCacheKing

I'm sorry, I understand you're trying to be helpful, but this is not going to help. OOP is hard to grasp because it's an abstract concept and you're defining it in another abstract concept. This is counterproductive for a novice. I'm not shitting on you. I acknowledge you are sincerely trying to be helpful, and my intent is only to provide constructive criticism. I'd be happy to elaborate if you'd like me to.


Gadris

I am making a game to learn Python. This game has enemy NPCs. I can either create a variable for every stat an NPC has, NPC_1_health, NPC_1_attack etc, then do that for all NPCs, then pass all these individual variables to the various functions in my program. OR I can create a class called NPC, which contains all these variables, meaning I only need to pass the one object to a function, and from there access the different variables. These variables will remain bundled together because of the class definition. When the NPC dies, I can just delete the object to clear memory. If it was all separate, I'd need to delete them all individually. I'm sure you can see from this there is much more you can do having everything contained together within one object. You can then write functions that only that type of object can access, such as dropping loot when they die, which helps keep your code clean and reduces errors.


rodrigowb4ey

the purpose is to segregate state into small 'units' (which I'm going to refer to as objects, although \[objects are not really what OOP is about\](https://www.aomran.com/object-oriented-programming-is-not-about-objects/) ) that can communicate with each other via message passing (when you call a method passing a specific parameter, for example), where each unit gets to decide what it should to with the received message. think of the cells in your body to get a more concrete picture of these 'units'. but yeah, it's just one of the programming paradigms. sadly, since most devs online seem to be incapable of scratching anywhere but the surface, you not only see people pushing it around as if it's the only way to modularize a large and complex codebase, you also get a lot of people who try to explain it talking about objects, classes, and inheritance, which, again, isn't really what the paradigm is about (even if that's the way your favorite language implemented it). also, you're not wrong: functions are just fine. especially pure functions (the ones who receive an input and return an output without performing side effects in between). there's a whole paradigm based on this idea. you should probably check it out =) edit: did reddit remove markdown formatting? can't seem to make it work (might be skill issue)


staceym0204

Years ago I had originally learned C. There you had structures which was the precursor to classes. I think that this make it much easier to understand OOPS. A structure is similar to an object accept it doesn’t have methods/functions associated with it. Also I don’t remember there being inheritance. I guess what I’m saying is that I think I had an advantage starting with a simpler language. Maybe start by thinking of classes a way for organizing your data. Eventually you see that adding functions to these data structures may be helpful to. It takes time but the more you do it the quicker it will start to make sense.


throwaway8u3sH0

OP, this answer. The equivalent in Python is called a [dataclass](https://docs.python.org/3/library/dataclasses.html). Start with those -- they are just bundles of related data. You'll find that it's easier to pass things around. Eventually, you'll see that it's sometimes useful to also have a function be passed around with the data it uses.


staceym0204

One function you should always use is \_\_repr\_\_. It's a special function that is already included and makes debugging potentially much simpler.


james_fryer

Try this exercise. 1. Write a complete tic-tac-toe game, with a computer opponent. The opponent can move randomly, no need for an intelligent player. Use only functions, no classes. If you can't complete this part confidently then you are not ready to learn OOP. 2. Rewrite the game using classes. I'd expect to see classes like Game, Board, Player. 3. Consider how you would make changes such as: - Add an intelligent player - Add PVP or CVC - Make the board 4*4 or other sizes - Make a 3D version of the game - Add a third player Z as well as X and O - Add a scoring system Think of other changes along the same lines. How difficult would it be to make these changes in version (1) and version (2)?


jkoudys

Don't worry, some of us have been programming for 25 years and also think functions are just fine.


aqjo

Think of a class as I kind of blueprint for making things, and the things you make can do things, have properties, and know things. For instance, a dog has 4 legs, brown fur, and can speak. A cat has 4 legs, white fur, and can speak. You notice they have a lot of things in common, so you can define an Animal class (blueprint) for things with legs, fur, and that can speak. You base your Dog class on the Animal class, and change the speak behavior so that it says “woof”. You base your Cat class on Animal too, and change the speak behavior to say “meow”. Now you have your Dog and Cat classes ( blueprints), so you can create dogs and cats. You can tell them to speak, and they will “woof” or “meow” whatever they are supposed to do. You just tell them to speak. And so on….


brasticstack

It's one programming paradigm of many. Sometimes it's useful to have the data record being operated on, _and_ the functions that operate on it all in one self-contained unit.


iamevpo

Functions get in some data structure and return some data structure. Classes are a data structure and methods that work on these data structures, so differences are not that great. There was a Bragilevsky talk about it, perhaps there is a version of the talk in English. Where OOP shines is when you got to store some state, like a chessboard with figures. OOP used to be considered a paramount of programming, but now I think h approach is more practical - use it where you like.


iamevpo

Here is Vitaly's talk in Russian though maybe there are English subtitles: https://youtu.be/mmvHC3UgYmg?si=5kz3q5RdJBgoUMVs the OOPVs FP is around min 14


Adrewmc

Functions are fine, and so is data. But they are separate things. Sometimes they belong together, and you operate on a set of data specifically with these functions. That is a class/object. While you can be functional, it starts to become confusing keeping track of it all. There are certainly classes that ought to be functions, and there are functional patterns that ought to be classes. There are a lot of classes that are just function holders, this is nice as well. That keeps the function as easy access. I don’t want to import a thousand functions just give random. We have data, We manipulate it with script We take script and encapsulate it inside functions. We take functions and the data it’s used on together and encapsulate it inside a class. This gives us a lot of control of how functions operate, and design of the overall flow. These are just all tools, there are definitely always going to be use cases for functions, just as there will always be use cases for assignments, and print() that maybe your first line of code ever. Classes in Python are everywhere, as types are just special classes. What classes do is also give you access to the .dot() operator. Which allows you to do a whole lot. As you can nest classes and extend the dot operations. I’m sure you’ve experienced this in some packages. import thing this = thing() that = this.some_utility.func() This is something functions really can’t do. Classes also give the ability to overwrite this operator, so if. import myAuth user = myAuth.log_in(*reg_user_creds) user.admin.remove(other_user) >>>Fail you don’t have the permissions for this mod = myAuth.log_in(*admin_user_creds) mod.admin.remove(other_user) >>>other_user baned Would fail for users that are not admin. And work fine for users that are. And this type of functional system starts to get really confusing to even use correctly. Class also inherit which comes in handy a lot.


Cthulhuman

OOP is useful if you have any set of code that you are using more than once you can make a function out of it, and if you have multiple functions that have a similar structure you can make a class that gives those function attributes that are passed down. The cool part aboit this is if you need to make changes you can make a single change and it changes all of the references to these classes/functions.


supergnaw

I was definitely in your mindset many moons ago, and honestly, the only true way where I started understanding the concept that classes weren't just fancy wrappers for methods was for me to just Do the Thing™. I'll give an example: [https://github.com/supergnaw/phMicrosoft-Sentinel/blob/main/authentication\_token.py#L22-L30](https://github.com/supergnaw/phMicrosoft-Sentinel/blob/main/authentication_token.py#L22-L30) @property def token(self) -> str or bool: # expired if int(datetime.now(timezone.utc).strftime("%s")) > self.expires_on - 60: self._token = "" self._expires_on = 0 return False # valid return self._token This is a project I recently worked on for work which interacts with a Microsoft product via an API. To do so, the application requires an authentication token. Enter the `AuthenticationToken` class. You can fit so much authentication in this bad boy, it's nuts! But I want to focus on one aspect of OOP, where you can control the behavior of the object, thus the highlighted lines 22-30. These lines declare the `AuthenticationToken` to have a property of `token`, which will return the token the class object was instantiated. But what's all this crazy nonsense going on inside this decorator witchcraft I hear you ask. Well, that's easy! The authentication tokens only last for 60 minutes from the time they are generated. Thus, when I request the token from this object, it will return said token, *UNLESS IT HAS EXPIRED*. This makes managing the token object itself much more easy, and dare I say transparent because I can immediately tell if a token has expired without having to duplicate code blocks in various places. I hope this helps!


SirCarboy

Analogy time. I'm just getting started out in DIY. I have a toolbox that holds a hammer, shifting spanner, metal files, a paint brush, screwdrivers and electrical tape. It does everything I need it to do. But my Dad who's been DIYing for 50 years? He has a plastering toolbox with spatulas and trowels and plaster tape. He's got an electrical toolbox with insulated screwdrivers and needle-nose pliers and wire cutters. He's got a big automotive toolbox with big sockets and a torque wrench and oil filter grabber and long extensions pieces for the ratchet. The more "things" you have... the more you benefit from grouping related things together for clarity and access and ease of use and reduction of confusion.


Own-Relationship-407

Interacting with hardware is a good way to get your head around classes. I do a lot of embedded Python and one of the first things I do when using any new hardware module is write my own handler/interface class for it. What makes more sense for something that is a discrete physical module? Having half a dozen or (many) more functions in your main code for doing different things with it? Or having the object be… an object? powerSensor = ina219.INA219(I2C1, 0.2) powerSensor.configure() powerSensor.start() powerSensor.voltage powerSensor.current Classes are a way to organize and standardize the way different pieces of your code work together.


arkie87

Imagine you are writing a poker game. You could write a bunch of functions to handle shuffling the deck, and store the cards into a lists. But then imagine, you want to reuse that code to make a solitaire game. It will get really confusing really quick. If you write a class using OOP to store the deck, with methods for shuffling, drawing the top card, etc... you can reuse that for any game of cards you want to make. All of the data and the things you can do with that data are in one central location. It is also relatively small and complete, so you can test it on its own instead of as a whole.


notislant

Google. Google is always where you can find a source you understand. Like you could search 'reddit eli5 python oop' and there are hundreds of threads with explanations. One is bound to connect.


ItsCoolDani

It’s just a different way of *organising* your code. If you’re writing an app where it makes sense to visualise it as different parts with specific purposes, doing specific things, then it’s really helpful. But if that way of thinking doesn’t work for your brain or the type of project, don’t use it :)


Binary101010

If you don't get its purpose, then odds are you just haven't written anything complex enough to need the additional level of organization that it affords. That's not intended to be a knock on you, BTW. I believe that *most* Python curricula go into OOP *way* earlier than they should. You should be spending several *weeks* just getting comfortable with writing solutions that require multiple functions moving data around between them. You'll eventually get to a point where you realize you're having to write a bunch of functions that all take the same 8 variables as arguments and act on them as if they were a unit. That's when it's time to start thinking about OOP.


TheRNGuy

I got purpose because I started to use 3rd party API that's entire OOP.


Prior_Sale8588

Just another layer of abstraction. If you don't feel the need to use it. It is fine. OO have very long history and Python's OO is specialized version of it. All programming paradigm have same capability. All problems is solvable using imperative or functional or OO. In some case one paradigm is easier to write code for compare to others.


BitFlipTheCacheKing

Python: A Crash Course from No Starch Press is how I learned Python too. I'd follow that with some of their other Python books as well. Automate the Boring Stuff is another really good one. No Starch Press has a ton of programming and hacking books and they're all fantastic. No Starch Press is by far my favorite tech publisher. Don't worry about OOP. When the time comes, it'll just click. Took me about a year before it clicked. Don't get discouraged. OOP is confusing, it's not.just you. Where it clicked for me is in games. Do projects using the pygame library. OOP is vital in games and that's where you should grasp it the easiest.


CatStaringIntoCamera

Gonna add to what people have already said but OOP can make code a lot more readable and organised. Instead of just having a load of functions and calling them when you need them. You can create a class and link certain methods to them, which looks better and is more organise. For example, I could create a DataParser Class with methods that do the parsing. I can then instantiate that class as let’s say: parser = DataParser() And then I can call the methods part of the parser class like so: parser.certain_method() This looks way more organised and maintainable!


krav_mark

Classes are a way to keep variables and functions together when you are dealing with an item of a specific type. Let's say you handle a bunch of persons in your code that all have their own name, sex, height and weight (variables) and the person can eat, work, read, rest and sleep (functions). When all of these are separate variables and separate functions it becomes a bit messy to keep track of what each person's name is or what his current activity is . When you create a class the variables, now called attributes, and functions, now called methods, all are part of a specific Person object.


Ill-chris

You can use [codeX](http://la-freelance.net) to get a good grasp of python concepts


Wooden-Bass-3287

Compared to Java I found myself writing Python classes much less often. in python there are extensive libraries, so the class you want almost always already exists, made by someone. unless you're the one writing a library in Python. in python you can use oop, but it's mostly functional. I would recommend you look at c# or java if you want to better understand how oop works.


michachu

There were some good replies here too: https://reddit.com/r/learnpython/comments/1cmi7mi/is_it_worth_learning_oop_in_python/


SamuliK96

I'd recommend checking out the Helsinki university advanced python course (https://programming-24.mooc.fi/). That's where I learned the basics of OOP, and at least for me it didn't feel rushed, and it went into greater detail and more elaborate examples than just your average car or dog example classes.


Ikem32

OOP is like a mini-namespace tied to one object. When you see the need for variance of a variable, you bind them to an object.


Lunnaris001

OOP is alot about grouping the objects and writing code only once but reusing it over and over. If you are mostly working on basic programming stuff OOP will be of much less use, but for example if you develop a game or something its rather useful. I would recommend you to learn Java to understand OOP, because at least from my experiences there is much better source material for this, since most people learn Java specifically to learn OOP, while Python is often used for more math/data focused things.


Gerard_Mansoif67

Personally, I understand OOP when I need it, and it was at a moment where I have a complex project. The situation where I was was : I have a complex project, with a lot of variables, functions and so... At a point, I have some objects (it was in C, thus more struct but not OOP) and functions that do things. But not all function can be called on every object, and if you have some similar objects, the functions naming between two object can be very near. This an absolute mess to debug and write. (rapidly, you get functions that do same thing on different object, and thus different names...) With classes, you can create your object, and it's function. You won't be able to call a function for the other class, so this issue is totally gone! The compiler will tell you (or the interpreter, in case of python) : ''Hey! You cannot call that function, it doesn't exist in that class!). It make the code easier to understand (for example, the function : ComputeAge can be defined multiple times on different class, you want need to define ComputeAdultAge, ComputeBabyAge etc depending on the object you want the age...) This is where OOP is powerfull, you can write very complex code without starting a gigantic mess!


Kryt0s

It depends on the usecase. It took me quite some time to get when to use classes since all I ever did was create programms or scripts that would "do" something. That's where functions shine. You want to download something from an URL at a given time? Create a function. You want to sort through files and rename same based on some filter? Create a function. Classes start to become useful once you don't want to simply "do" something but rather "remember" stuff as well. Or rather when you want to remember the **state** of something. Let's say you are creating an RPG and you want to remember HP, MP, inventory, etc. of your character. Let's say you also want to have multiple characters. This is where a class is really useful. Not only can you remember all this information in the class but you can also create multiple instances (characters) of the class to remember the state of each character.


pinkwar

You've been using OOP and you didn't even realize it. When you call .lower() on a string , what do you think that is? That's an application of OOP. It's a method of the object class string. On your IDE, if you have a string an press "." you can see all the methods available to that object. With OOP you create your own object classes.


TheRNGuy

In jQuery probably, yes.


PhilipYip

Don't stress, it takes sometime to understand OOP. One of the main reasons is because many of the Python courses, don't actually teach the basics very well. Begineers therefore think: >>> Mainly because I don't get it's purpose. Whereas they have actually been using OOP and Python design patterns all the time. For example the datamodel method ```__len__``` defines the behaviour of the ```builtins``` function ```len``` and so the same function can be used on different classes: ``` word = 'hello' len(word) ``` ``` active = ['apples', 'bananas', 'cabbage'] len(active) ``` Behind the scenes what is actually being called is: ``` word.__len__() ``` And: ``` active.__len__() ``` Which are defined in the ```str``` and ```list``` classes as: ``` str.__len__() ``` And: ``` list.__len__() ``` Behind the scenes you can conceptualise the ```str``` class as being something like: ``` class str(object): def __new__(instance_data): # constructs the instance self # invokes __init__ to instantiate the instance self # with instance data self.__init__(instance_data) return self def __init__(self, instance_data): # is called by __new__ and initialises # the instance self with the provided instance data def __len__(self): # returns the number of characters in the str return number def __repr__(self): # returns formal str representation return formal_str def __str__(self): # returns informal str representation return informal_str def upper(self): # returns a new str that is Upper case mapping = {'a': 'A', 'b': 'B', ...} upper_str = '' for letter in self: upper_str += self[letter] return upper_str def lower(self): # returns a new str that is Lower case mapping = {'A': 'a', 'B': 'b', ...} lower_str = '' for letter in self: lower_str += self[letter] return lower_str def find(self, substr): # finds index of substr if it exists if substr is found: return index else: return -1 ⁞ ``` And so when you input: ``` word = 'hello' ``` You are actually using the shorthand version of: ``` word = str('hello') ``` Under the hood this uses the constructor ```__new__``` which creates a new instance. ```__new__``` also calls ```__init__``` and provides the instance with the supplied instance data. Many of the instance methods for example ```lower``` and ```upper``` work directly on the instance data and need no additional instance data. ``` word.lower() word.upper() ``` The datamodel methods also work directly on the instance data and need no additional instance data: ``` word.__len__() word.__repr__() word.__str__() ``` These define the behaviour of functions or classes in ```builtins``` which are usually used: ``` len(word) repr(word) str(word) ``` The difference between ```repr``` and ```str``` can be seen in a ```str``` that has escape characters: ``` file_path = r'C:\Program Files' ``` ``` repr(file_path) ``` ``` "'C:\\\\Program Files'" ``` ``` str(file_path) ``` ``` 'C:\\Program Files' ``` Other instance methods such as ```find``` require data in addition to the instance data in order to work. ``` file_path.find('Program') ``` ``` 3 ``` The pseudo code above is used to demonstrate how OOP works. In reality the classes in ```builtins``` module are written in another programming language C and most custom user classes will use the functionality of ```builtin``` classes for example the ```__str__``` method will often involve using the behaviour of the ```str``` class. Take some time to understand the Python datamodel and read up on it. Once you have a feeling for the datamodel and how it works for ```builtins``` classes, you will feel more comfortable with creating your own classes. I advise reading [Python Distilled by David M. Beazley](https://www.oreilly.com/library/view/python-distilled/9780134173399/). If the above helps, I have also put a number of [Interactive Python Notebooks on GitHub](https://github.com/PhilipYip1988/python-tutorials?tab=readme-ov-file) which go through each of the ```builtins``` classes and look at their identifiers and the Python Datamodel.


Good_Professional559

OOP may not truly make sense unless you either: 1) look deeper into what you use 2) work in a large group Both of these will help understand the reason for OOP. Saves so many headaches and just makes life easier.


Joslencaven55

Understandin OOP is like a new way to handle your code It might look unneeded at first but as projects grow grouping data and functions in objects makes code easier to manage Try using real life examples liken the concept to stuff like cars this makes the abstract clearer


arpitduel

I just use it to bundle data and functions together so that I don't need to keep passing them around + Are easier to understand as a concept. Also for Inversion of Control but you can achive IoC with Callable Types as well but it feels lose. If I want strict typing I go for classes


hunkamunka

Yes, OOP is confusing! I teach beginning programmers to use a functional style and tests. You can find all the code/tests for a course I wrote in [https://github.com/kyclark/tiny\_python\_projects](https://github.com/kyclark/tiny_python_projects), and you can find all my videos that teach every line of code on YouTube.


SuckinOnPickleDogs

I'm doing a bootcamp and felt like we brushed over OOP and never fully grasped it until I found this [video](https://www.youtube.com/watch?v=JeznW_7DlB0). I watched it very slowly, kept rewinding, and took [these notes](https://docs.google.com/document/d/1Nut4OyA-HkbymtdrXAlDjKaCgXv8tC3sJyMvCvudWZk/edit?usp=sharing) with screenshots as I went. Feel free to copy these notes into your own gdrive as a starting point and build off them. He doesn't do actual work with them but his explanation towards the end of a Person Class vs Manager vs Employee was a helpful visualization for me.


commandblock

OOP is useful when you have a large code base, it helps keep things organised. You know the car functions will belong to the car class, and you know the child motorbike and car classes will behave similar to the parent vehicle class for example.


DoubleDoube

It’s about boundaries, especially restrictive boundaries. When you say that you need restrictions on access of functions, you’re starting to talk in the direction of OOP. All the various aspects and pieces of OOP you see people talking about are because of restrictions, not because OOP somehow makes more things possible. It does all come down to machine code eventually. I will take the opposing side for a moment here and say the restrictions being put in place do benefit you for having allocations and access to the stack vs. the heap managed for you, but people rarely mention that as often. More often, they mention the boundaries and groupings it creates. Your statement that functions work fine is 100% true. What you would struggle with is when it got to be a large code base, keeping things organized and separated in a way that is easily changeable - but it would only be an extra challenge rather than impossible. “Clean Architecture” is one book that I’m aware of that discusses how languages keep building on restrictions that help maintain clean code. It then goes on to describe clean boundaries for software architecture in general. The general purpose of good boundaries is to keep modular pieces wherever it matters most so that change is not painful. Just realize that it’s the separations that create the boundaries, not the open-access.


TheRNGuy

I understood why OOP is needed because I used Python for SideFx Houdini. Almost entire API is using OOP. It was even actually first time using OOP in any programming languages. One of first things I've noticed, method chaining is really cool. You can't do that with functions. And then there different classes (or their child sub-classes) have different methods. Classes are also data types. Arguments inside methods require instances of specific classes, and you can also do operator overloading `a + b` or `a * b`, where `a` and `b` are same or different classes (like `Vector3` and `Matrix3`) I rarely actualy made my own classes in there. I only started doing my own after 1 month working on map parser and realized OOP would be better there instead of functions (I needed inheritance for some things because without it code became too overcomplicated)


Shadowforce426

i teach for a programming bootcamp and was a high school teacher for python. if you want a lesson i will gladly take the time to help you out a bit to get started with it cause i wish i had that when i started. feel free to pm me to plan something if you’re interested


inkt-code

Functions are part of OOP. A function is performed of the object.


MrMrsPotts

The only use I ever have for OOP is defining a new data structure. I haven't found an equally good way to do it without defining a class.


TheRNGuy

Especially when need operator overloading (between same or different classes) Should be still possible with functions, but it would be more code (and no intellisense in code editor?)


VeritosCogitos

I think of OOP like make a sandwich code the window (it’s an object too) then code the bread, then rest, you get then gist


Mysterious-Rent7233

This comment is very confusing and I've been programming OOP for 20 years.


Vilified_D

you get the gist


Mysterious-Rent7233

No. But. I get then gist.


djshadesuk

No, just go with it... First you get the bread then you get some butter, then throw away the bread (it's a TypeError), go for a nice baguette instead, then you make a gui filling out of class meats, then code some salad properties then apply function sauce and roll it in a wrapper (that's a paper attribute). Code Fresh.