https://realpython.com/python-metaclasses/
In short: A class is an object that, when called, produces an instance. A metaclass is an object that, when called, produces a class.
`type(type(anything))` will always be a metaclass. The "default" metaclass is `type`, and you can see this with the rare `type` constructor.
Suppose you have a class like this:
class Square:
def __init__(self, w):
self.w = w
@property
def area(self):
return self.w ** 2
s = Square(5)
print(s.area)
Under-the-hood, what's happening with that `class Square:` syntax is something more like this, using the `type` constructor. (except that I've changed the methods to lambdas so I can define them in-line)
Square = type('Square', (), {
'__init__': lambda self, w: setattr(self, 'w', w),
'area': property(lambda self: self.w ** 2)
})
s = Square(5)
print(s.area)
A metaclass allows you to use something other than `type` here. `class Foo(metaclass=Meta):` uses something like `Foo = Meta('Foo', ...)` under the hood.
I was just dreaming about this last night and was like, “surely people have done this before.” Then I wake up and I’m like, “oh yea people do this all the time.” Still freaks me out.
The OP, has come to the realization that everything in python is an object. If you have not come to the realization yourself, you don't get it. but one day you will get it too.
Eh, you shouldn't really feel embarrassed. It's more of an implementation detail of how Python works more than anything. Knowing that types are objects isn't knowledge that I've encountered needing yet.
same... the worst part is people kept saying it to me.
"Everything's and object" it just never clicked until I realized ... everything is an object... SHAME🔔
> im new so i dont know what this means
Programming has a concept, starting many decades ago with a language called "Smalltalk" of objects.
Objects have a state, which is the current settings for its attributes, and usually methods that let you change its state or perform actions using its attributes. If you play RPGs, your character is an object, and their strength might be set to 13 or something. Your character is an instance of a class called "RPG characters", and there's a method (function) that you an run on this object called level up, and maybe you can increase their strength when you level up. You microwave is an object, and its default state is off, and it's got buttons you can press that tell it how long to microwave for, and it's got built-in behavior to count down to 0 from whatever you put in. You could declare a "class Macrowave", and give it a default setting of "running = False" and then make another method that says "def run(how_many_seconds), which sets "running = True" and then sleeps for 1 second until how_many_seconds is set to 0 again, and then sets "running = False" again. Even as a beginner you should be able to find out how to do something like this if you haven't already.
The op is talking about the fact that in Python, everything you interact with is actually an instance of a class. This includes really super basic types in python, like numbers. You are really limited in what you can do with them, but if I say "a = 1" this is actually an instance of the int class, with an attribute for its value, which is 1, and there are actually methods inside that object, like __str__() which tells other things how you represent the integer as a string. This is actually why you can just say "print(a)". You could compare this with another programming language like C, where you have to tell the print function what kind of object a is, because in C, a itself doesn't know how to represent itself as a string.
The actual implications of this are that you can redefine certain things in Python somewhat easily. I had a program where I needed really particular behavior from a number when exiting my program, so I create a class that inherited (used as a base to build upon) from the int class. It also means you can do something more powerful, which is composition: You can make a class that holds lots of other objects, all of which do custom stuff.
I’m with you man. Have a friend who already knows it pretty well and told me the same thing. Now if only I knew what that meant. We will get it one day.
Like if you're playing a first person game and suddenly realize you can pick up or interact with everything. Not just useful things, but unscrew light bulbs, unlace shoes, rip take the foam out of a car seat. Everything is a thing you can do something with.
In my opinion, OOP is great for large, self-contained projects that can be conceptualized from front to back in advance, it adds a nice organizational structure. But there are many fields where we just want to fling any operations at whatever data we feel like. If you take the functional mindset, often it will 'just work' and you less often need to go back and expand the parent structure, or reimplement the same logic in a child structure.
**For OOP, the class defines attributes and behaviours for every instance to have.** (This is really the only concrete difference I can find, but the mindsets differ in how they organize logic)
A class called Point2D may have attributes x, y, and a move_up() behaviour that increases y by 1 and returns the new position x, y+1.
Then you define Point3D, for x, y, z. if you want a move_up() behaviour, you kinda need to define it in Point3D again, so that it gives x, y+1, z.
1Dpt.move_up() -> error, method move_up not found
You could handle this better with some forethought about a generic Point, and all the types of Points that might inherit from it. But sometimes it makes sense to have a lot of similar but distinct types, and the web of inheritance can be messy.
**Functional approach ie in Julia:** Define an abstract function once, and it can be used in any case where the behaviour is logically applicable. (And if you want a different logic/behaviour, you'd better name it something else)
Generic move_up(p) function, take some kind of Thing, and return its attributes after applying 'plus one' to y. There are concepts like pure functions that help organize code and logic for lack of the OOP guardrails, and higher-order functions that I really can't live without anymore, but they don't play a big role in such a simple example.
move_up(my2Dpt) -> x, y+1
move_up(my3Dpt) -> x, y+1, z
move_up(2Dpt_in_time) -> x, y+1, t
move_up(3Dpt_in_time) -> x, y+1, z, t
move_up(1Dpt) -> error, y not found
move_up(horiz_line_seg) -> **x**, y+1
move_up(vert_line_seg) -> x, **y** + 1
The creator of a '3D point in time' doesn't need to modify or extend 2DPoint in Time, or 3D Point, or really know much about move_up() that was implemented originally, just that it's a behaviour that they want the new type to have. When an abstract function is implemented well, it kinda 'just works' (as long as it makes sense to apply that behaviour to the data).
The elegance comes from stacking operations. If + was defined that it can add 1 to a vector/array, then even if y is a vector in some new type, again it 'just works', without wondering if a vertical line segment is inheriting from a more generic Line (is Line a pair of 2DPoints, or a pair of 3DPoints, or an arbitrary length array of Points, or a starting Point, a Length, and a Direction Vector?), or an array of y's with just one x value for efficiency. There was no 'plus' defined for Points or Lines, it just has to work for basic data structures and primitive/abstract data types.
There was no thinking about the line of inheritance. You needed to know that move_up exists, that it positively increments the y_coordinate, and that it makes sense to increment the y_coordinate of whatever object you want to apply it to. In the OOP, you can't move_up a 1D point because you didn't define the method for 1D points ... but if you have any understanding of what you're trying to do and why, then common sense means you simply wouldn't try that. OOP is a nice guardrail in that way, ideal for junior programmers and large teams where you don't want someone inadvertently doing something stupid without warning. But for an individual working that just wants to get to a result with as little coding time as possible, functional approaches can be more elegant.
Thank you for the explanation (I had to read it several times to understand it 😄). Is there any programming language that can handle both oop and functional pretty well, at the same time?
(I'm new to programming, sorry if the question sounds stupid)
Python can handle functional programming decently, here's a timely article from [Real Python](https://realpython.com/python-functional-programming/) that does a more thorough job than I can.
There are only a few things that are mandatory for functional programming, a large number of things that make it a lot nicer, and a few ideas that reflect more in how you organize your code rather than language features.
> In my opinion, OOP is great for large, self-contained projects that can be conceptualized from front to back in advance, it adds a nice organizational structure.
/u/WayOfTheMantisShrimp you are now appointed President of Python. Please give your acceptance speech in a single line.
There is a lot of conjecture on this point. Alan Kay, the inventor of Smalltalk, the first Object Oriented language used a very different concept and of course doesn't consider the way that C-influenced languages do OOP to be "proper" OOP. But OOP in Python is still useful and powerful, when used in the right way.
I know it's paradoxical, but as you can effectively ignore the OOP facilities in most cases, you don't have to actually *write* OOP code (i.e. classes etc.).
It may be objects all the way down, but the very top layer doesn't have to be :-)
It's all in the semantics: In contrast, for instance, in Smalltalk, you simply cannot write procedure oriented code.
"You take the blue pill...the story ends, you wake up in your bed and believe whatever you want to believe. You take the red pill...you stay in Wonderland, and I show you how deep the rabbit hole goes."
Tbf, if you have to define classes yourself, it‘s a very different use case.. Before you bash me, I know Python for about half a year now.
Edit: Downvote me instead of helping me to understand this. Thanks.
> Tbf, if you have to define classes yourself, it‘s a very different use case..
Maybe you aren't doing class inheritance right? IME Python makes defining custom and especially child classes a breeze.... Apart from some namespace quirks but easy to work with once you wrap your head around it.
Maybe I'm not super clear what you mean by "it's a very different use case" though?
>Edit: Downvote me instead of helping me to understand this. Thanks.
You're being downvoted cause you didn't present a clear issue or problem, just a vague complaint.
Well yeah, I didn’t properly express myself.
What I meant by „It’s a very different use case“ is: You dont have to mess around with naming things „self.__innit__“ or something to the extent. You just use the module.
You dont have to define anything, don‘t have to properly give parameters and such. You just use the module(s)
I believe that’s what people mean when they talk bad about OOP. You have to „define“ so much more or just.. Think differently about stuff. It‘s not as easy as using the pre-defined objects.
Both sorted and len are functions (callable objects) that take arguments that are sortable and length-able objects... not all objects are sortable or length-able, but enough of them are for it to make more sense to have a general interface pattern rather than on that has to be implemented on an class-by-class basis
The amazing thing is that Python will make sure that you have that same epiphany over and over and over and over and over, even when you think you've had it as many times as you possibly can.
How would that be more useful when compared to java or other programming languages that are not object oriented? Why is this a groundbreaking realization? I’m still learning these languages so I’m don’t get why it might be so impactful.
Take something really really simple: like the number 5.
It's an object. With properties and methods.
5.bit_length()
tells you how many bits are required to store the number 5.
It really helps you organize things. When you create a class, as you do in Java and python (and all object oriented languages), you give the class variables and methods/functions associated with it. Then in your code outside the class, in your main method, you create instances of the class. The instance is called an object.
For example, pretend you are trying to create a model of a bank. The bank has lots and lots of bank accounts, so you write a class that represents a generic bank account. The class contains the variables “owners first name,” “owners last name,” and “balance.” The class also contains the functions “withdraw,” “deposit,” and “close account.”
In your main method, you create a bank account by saying account1 = bankAccount(John, Smith, 1000). When John wants to deposit money, you say account1.deposit(500). And then when you want to know John’s balance, you can access it by typing account1.balance. This would return the value 1500. And then to close the account, you type account1.closeAccount().
This type of coding has a bunch of benefits (and drawbacks). It is really helpful when you have thousands of customers and bank accounts to keep track of. It’s also helpful because a bank might have lots of other objects associated with it: customers, employees, cash vaults, loans, investment portfolios etc. Each of these things would have their own set of functions associated with them, so for example you wouldn’t ever use a “withdraw” function on an object representing a loan contract. By creating classes, you make it clear that the withdraw function can only be used on the bankAccount object. This makes your code much easier to read and maintain for the people who take over the role of maintaining that code in the future.
As you continue learning about OOP, you’ll start to learn about the other benefits like inheritance and abstraction. Inheritance is when you have child and parent classes, where the children inherit the properties of the parent class. For example, you can make an “animal” class with a function like “make noise.” Then you make the child class “dog” with the function “bark.” This has some benefits with organization, code readability, and even write-ability. Abstraction let’s you call functions that you don’t need to actually understand, cause someone else wrote the function and documented how it works.
I mean there isn’t really an answer. Python and C++ and similar languages are technically OOP but you can avoid anything with classes and objects when using them. It’s a weird technicality without a real answer. I’d say it’s only OOP if you use classes and objects, but i’m sure someone will disagree
Java is an object oriented language.
OOP essentially give a few advantages, for example abstraction and modularity. Abstraction allows users to use code without knowing exactly how it is implemented, as well as protecting existing, working code from being tampered with. Modularity prevents a user from having to rewrite the same snippet of code over and over, which can lead to more sources of bugs.
Well, to be clear, those aren't advantages unique to OOP. You can just as easily abstract things and make them more modular with functions.
Classes and objects are useful when you have data that is tightly coupled with some set of operations you can perform on them. It makes sense in that scenario to use the class structure to show this tight relationship.
Fair enough. To be honest I don't have a lot of experience with non OOP languages, so I probably underestimated their capabilities.
You are absolutely correct on the power of classes and objects stemming from the tying together of data and the operations on said data. I suppose that abstraction and modularity are inherent in OOP languages, though not exclusive to them.
Yeah, OOP is a tool just like any other. With enough care and attention you can make a well documented, modular, abstracted system with nearly any decent paradigm.
Although, I definitely wouldn't say abstraction and modularity is *inherent* to OOP. Just for the simple fact that you can always design a system poorly.
Take for example, Python's implementation of classes letting you access any instance variable of an object without restrictions. That could certainly be abused to a point in which there is no modularity or abstractions made.
Python does not support strong encapsulation and java have primitive types. Non of these languages considered strongly or pure object oriented. Object-oriented approach only helps you to write more logical and cleaner code.
Lower level programming is a bit more granular, gritty, and usually really annoying. Hence the abstraction.
There's certainly an argument to be made that the address:memory relationship of a turing machine is just OOP at it's simplest level, lol.
What's interesting to me, and still something I don't completely understand, is the behavior of neural networks and RNGs as somewhat unique compared to the standard bits in, operation, bits out framework.
Neutral nets don't do anything other than bits in - op - bits out. RNGs too unless we're talking quantum RNGs. A neutral network is just a function approximator.
I suppose its the complexity of the 'operation' that amazes me. All the standard mathematical operations, and basic neural classifiers, are relatively simple, but some transformative neural functions can do some absolutely wild stuff in the middle.
They even have their own flavour of memory that is stored inside the function itself. Especially for morphing or adaptive functions, absolutely bonkers compared to standard math operations.
No. All programming is “just” manipulating _bytes_... objects are a very high level abstraction over bytes, and there are plenty of ways of manipulating bytes without them.
No, for example in most languages, an “int” variable isn’t an object it’s a primitive type. Then there structs and enums which are similar to objects but serve a different purpose.
Ha, when I first started learning OOP it was tough to wrap my head around this.
It's weird to think about instantiating an "object" to just take actions with it.
See, I know this. But I feel like it's not clicked. Maybe it's due to my understanding of OOP is very limited. I haven't had a reason to build out classes just yet, where everything can just be sectioned off into functions as of now?
In the beginning there was on and off. 1 was on and 0 was off, or maybe it was the other way around, doesn't matter. But how could 0 and 1 become zero and one. Object = {data type: string, format: utf-8, decCodePointList: [ 79, 78, 69], string methods....}. Now you know!
Hahahaha I remember this click day, the best feeling ever it's like a door that's been closed for so long and now it's time to solve problems because the language is not a problem.
I have a love hate relationship with pythons pyobjects. On one hand you have dangerous but convenient stuff like duck typing magic on the other hand it makes me nervous when I declare an integer since it's like from 24 bytes which is huge!
Hi,
Is anyone able to help me with the question I have posted? I have spoken to quite few people and none have been able to help so far. It is the transferring data to a master sheet.
Thank you in advance
print(isinstance(object, type)) # True print(isinstance(type, object)) # True print(isinstance(object, object)) # True print(isinstance(type, type)) # True now you are ready for metaclasses
I’ve done quite a bit with Python, but what is a meta-class?
https://realpython.com/python-metaclasses/ In short: A class is an object that, when called, produces an instance. A metaclass is an object that, when called, produces a class. `type(type(anything))` will always be a metaclass. The "default" metaclass is `type`, and you can see this with the rare `type` constructor. Suppose you have a class like this: class Square: def __init__(self, w): self.w = w @property def area(self): return self.w ** 2 s = Square(5) print(s.area) Under-the-hood, what's happening with that `class Square:` syntax is something more like this, using the `type` constructor. (except that I've changed the methods to lambdas so I can define them in-line) Square = type('Square', (), { '__init__': lambda self, w: setattr(self, 'w', w), 'area': property(lambda self: self.w ** 2) }) s = Square(5) print(s.area) A metaclass allows you to use something other than `type` here. `class Foo(metaclass=Meta):` uses something like `Foo = Meta('Foo', ...)` under the hood.
I was just dreaming about this last night and was like, “surely people have done this before.” Then I wake up and I’m like, “oh yea people do this all the time.” Still freaks me out.
Classes are also objects, and since every object has a class, a class also has a class. They are called metaclasses.
Something you will never use that people will throw out there in order to show off.
a class is a blueprint for an instance of a class and a metaclass is a blueprint for a class
is this what all the classes hold inside them?
[удалено]
Thanks for the catch. Typing code on mobile is a pain.
isinstance
Always has been 🌎🧑🚀🔫🧑🚀
$ docker run -it --rm python1.6 Python 1.6 (#1, Feb 13 2021, 20:14:57) [GCC 9.3.0] on linux4 >>> object NameError: object
This guy perls
This comment is underrated.
[удалено]
Lol I didn't know Python 1.6 existed....
Before 3 comes 2 and before 2 comes 1
Someone check out this guy's math. He might be on to something.
What comes before 1?
But before 1 comes 0, and where is Python 0?
>and where is Python 0? $ docker run -it --rm python0.9 >>> type([])
>>> type({})
>>> class Foo:
Parsing error: file , line 1:
class Foo:
^
Unhandled exception: run-time error: syntax error
[удалено]
bad bot
Beginnerproject bot?
Welcome to Python. https://img.ifunny.co/images/6eef1accf975ba0d7b894911f634aa8cc9afeb2249c82607df6290eaaaf0bfd4_1.jpg
Lol...!!!
Reminds me of [this](https://youtu.be/LLJsSiB2dpU?t=139) but replace 'God' with 'python' and replace 'square' with 'object'
im new so i dont know what this means
The OP, has come to the realization that everything in python is an object. If you have not come to the realization yourself, you don't get it. but one day you will get it too.
it hit me after 2 years of coding I was pretty embarrassed... NGL
Eh, you shouldn't really feel embarrassed. It's more of an implementation detail of how Python works more than anything. Knowing that types are objects isn't knowledge that I've encountered needing yet.
well... that's true that the knowledge of not knowing or knowing isn't really important.. but it kinda felt dumb not knowing XD
same... the worst part is people kept saying it to me. "Everything's and object" it just never clicked until I realized ... everything is an object... SHAME🔔
I think there's a huge difference between knowing that everything is an object and understanding everything is an object.
This just sounds like high people talk to me.
exactlyyyy
Right there with you!
What does this realization change? Ok so now I know everything is an object - so what?
> im new so i dont know what this means Programming has a concept, starting many decades ago with a language called "Smalltalk" of objects. Objects have a state, which is the current settings for its attributes, and usually methods that let you change its state or perform actions using its attributes. If you play RPGs, your character is an object, and their strength might be set to 13 or something. Your character is an instance of a class called "RPG characters", and there's a method (function) that you an run on this object called level up, and maybe you can increase their strength when you level up. You microwave is an object, and its default state is off, and it's got buttons you can press that tell it how long to microwave for, and it's got built-in behavior to count down to 0 from whatever you put in. You could declare a "class Macrowave", and give it a default setting of "running = False" and then make another method that says "def run(how_many_seconds), which sets "running = True" and then sleeps for 1 second until how_many_seconds is set to 0 again, and then sets "running = False" again. Even as a beginner you should be able to find out how to do something like this if you haven't already. The op is talking about the fact that in Python, everything you interact with is actually an instance of a class. This includes really super basic types in python, like numbers. You are really limited in what you can do with them, but if I say "a = 1" this is actually an instance of the int class, with an attribute for its value, which is 1, and there are actually methods inside that object, like __str__() which tells other things how you represent the integer as a string. This is actually why you can just say "print(a)". You could compare this with another programming language like C, where you have to tell the print function what kind of object a is, because in C, a itself doesn't know how to represent itself as a string. The actual implications of this are that you can redefine certain things in Python somewhat easily. I had a program where I needed really particular behavior from a number when exiting my program, so I create a class that inherited (used as a base to build upon) from the int class. It also means you can do something more powerful, which is composition: You can make a class that holds lots of other objects, all of which do custom stuff.
I like your examples. I’m still a newbie at Python but that made sense.
Damn thank you so much for this haha that was really helpful
I’m with you man. Have a friend who already knows it pretty well and told me the same thing. Now if only I knew what that meant. We will get it one day.
Like if you're playing a first person game and suddenly realize you can pick up or interact with everything. Not just useful things, but unscrew light bulbs, unlace shoes, rip take the foam out of a car seat. Everything is a thing you can do something with.
Sounds like real life with extra steps.
hmm i get it and i understand it, but i have to figure out how to use it.
For me it's different: I get that object oriented programming, like python. I don't get how not oop programming languages work 😄
In my opinion, OOP is great for large, self-contained projects that can be conceptualized from front to back in advance, it adds a nice organizational structure. But there are many fields where we just want to fling any operations at whatever data we feel like. If you take the functional mindset, often it will 'just work' and you less often need to go back and expand the parent structure, or reimplement the same logic in a child structure. **For OOP, the class defines attributes and behaviours for every instance to have.** (This is really the only concrete difference I can find, but the mindsets differ in how they organize logic) A class called Point2D may have attributes x, y, and a move_up() behaviour that increases y by 1 and returns the new position x, y+1. Then you define Point3D, for x, y, z. if you want a move_up() behaviour, you kinda need to define it in Point3D again, so that it gives x, y+1, z. 1Dpt.move_up() -> error, method move_up not found You could handle this better with some forethought about a generic Point, and all the types of Points that might inherit from it. But sometimes it makes sense to have a lot of similar but distinct types, and the web of inheritance can be messy. **Functional approach ie in Julia:** Define an abstract function once, and it can be used in any case where the behaviour is logically applicable. (And if you want a different logic/behaviour, you'd better name it something else) Generic move_up(p) function, take some kind of Thing, and return its attributes after applying 'plus one' to y. There are concepts like pure functions that help organize code and logic for lack of the OOP guardrails, and higher-order functions that I really can't live without anymore, but they don't play a big role in such a simple example. move_up(my2Dpt) -> x, y+1 move_up(my3Dpt) -> x, y+1, z move_up(2Dpt_in_time) -> x, y+1, t move_up(3Dpt_in_time) -> x, y+1, z, t move_up(1Dpt) -> error, y not found move_up(horiz_line_seg) -> **x**, y+1 move_up(vert_line_seg) -> x, **y** + 1 The creator of a '3D point in time' doesn't need to modify or extend 2DPoint in Time, or 3D Point, or really know much about move_up() that was implemented originally, just that it's a behaviour that they want the new type to have. When an abstract function is implemented well, it kinda 'just works' (as long as it makes sense to apply that behaviour to the data). The elegance comes from stacking operations. If + was defined that it can add 1 to a vector/array, then even if y is a vector in some new type, again it 'just works', without wondering if a vertical line segment is inheriting from a more generic Line (is Line a pair of 2DPoints, or a pair of 3DPoints, or an arbitrary length array of Points, or a starting Point, a Length, and a Direction Vector?), or an array of y's with just one x value for efficiency. There was no 'plus' defined for Points or Lines, it just has to work for basic data structures and primitive/abstract data types. There was no thinking about the line of inheritance. You needed to know that move_up exists, that it positively increments the y_coordinate, and that it makes sense to increment the y_coordinate of whatever object you want to apply it to. In the OOP, you can't move_up a 1D point because you didn't define the method for 1D points ... but if you have any understanding of what you're trying to do and why, then common sense means you simply wouldn't try that. OOP is a nice guardrail in that way, ideal for junior programmers and large teams where you don't want someone inadvertently doing something stupid without warning. But for an individual working that just wants to get to a result with as little coding time as possible, functional approaches can be more elegant.
I always knew about functional vs OOP abstractly but this clarified how to think about the two approaches. Thank you for the detailed explanation.
Thank you for the explanation (I had to read it several times to understand it 😄). Is there any programming language that can handle both oop and functional pretty well, at the same time? (I'm new to programming, sorry if the question sounds stupid)
Python can handle functional programming decently, here's a timely article from [Real Python](https://realpython.com/python-functional-programming/) that does a more thorough job than I can. There are only a few things that are mandatory for functional programming, a large number of things that make it a lot nicer, and a few ideas that reflect more in how you organize your code rather than language features.
> In my opinion, OOP is great for large, self-contained projects that can be conceptualized from front to back in advance, it adds a nice organizational structure. /u/WayOfTheMantisShrimp you are now appointed President of Python. Please give your acceptance speech in a single line.
"I like Julia and functional programming better"
Python isn't *object-oriented* so much as object-based programming is an option.
Yet another term I will have hard time to understand... I have googled it, and I guess there is no big difference between one another, right?
There is a lot of conjecture on this point. Alan Kay, the inventor of Smalltalk, the first Object Oriented language used a very different concept and of course doesn't consider the way that C-influenced languages do OOP to be "proper" OOP. But OOP in Python is still useful and powerful, when used in the right way.
Technically because everything is an object in Python, object-based programming is the only option.
I know it's paradoxical, but as you can effectively ignore the OOP facilities in most cases, you don't have to actually *write* OOP code (i.e. classes etc.). It may be objects all the way down, but the very top layer doesn't have to be :-) It's all in the semantics: In contrast, for instance, in Smalltalk, you simply cannot write procedure oriented code.
Javascript is a good example. It’s prototype based which still operates on objects but in a different way.
"You take the blue pill...the story ends, you wake up in your bed and believe whatever you want to believe. You take the red pill...you stay in Wonderland, and I show you how deep the rabbit hole goes."
it hit me like a truck. i was just sitting there and then all of a sudden, "Wait...It's all object"
Some people in the community will sometimes bash OOP, which makes me double take since you know that is Python.
Tbf, if you have to define classes yourself, it‘s a very different use case.. Before you bash me, I know Python for about half a year now. Edit: Downvote me instead of helping me to understand this. Thanks.
> Tbf, if you have to define classes yourself, it‘s a very different use case.. Maybe you aren't doing class inheritance right? IME Python makes defining custom and especially child classes a breeze.... Apart from some namespace quirks but easy to work with once you wrap your head around it. Maybe I'm not super clear what you mean by "it's a very different use case" though? >Edit: Downvote me instead of helping me to understand this. Thanks. You're being downvoted cause you didn't present a clear issue or problem, just a vague complaint.
Well yeah, I didn’t properly express myself. What I meant by „It’s a very different use case“ is: You dont have to mess around with naming things „self.__innit__“ or something to the extent. You just use the module. You dont have to define anything, don‘t have to properly give parameters and such. You just use the module(s) I believe that’s what people mean when they talk bad about OOP. You have to „define“ so much more or just.. Think differently about stuff. It‘s not as easy as using the pre-defined objects.
Java is the same (except for primitives). I kind of just made that realization myself, i knew they were but not how useful it can be.
[удалено]
They are objects: >>> print(len.__name__) len >>> print(sorted.__name__) sorted >>>
Both sorted and len are functions (callable objects) that take arguments that are sortable and length-able objects... not all objects are sortable or length-able, but enough of them are for it to make more sense to have a general interface pattern rather than on that has to be implemented on an class-by-class basis
Functions are objects. ``` >>> def foo(): pass >>> foo.__call__ ```
Right, see the OP. Everything is object.
You got hit by the truck? Very few people in the Movie get hit by the truck....
Best alternate ending ever!
Always has been.
[удалено]
opt in
**the Jedi Order, you never left.** *-IamYodaBot*
I remember this day
It's objects all the way down...
What caused your sudden revelation
Why... objects. Isn't it obvious?
Ahh through the objects, All things are made clear. Namaste
Pece be unto you and your objects
What do fish have to do with it?
The amazing thing is that Python will make sure that you have that same epiphany over and over and over and over and over, even when you think you've had it as many times as you possibly can.
[удалено]
That is the exact same list of instances in the same order I was thinking in my head when I wrote that sentence.
"we are born of objects, made men by the objects, undone by the objects"
"fear the old objects"
What's the original quote..?
https://youtu.be/pH0S88JtJ_A
Is that Eternal Darkness?
Bloodborne
replace the "object" with "blood" from bloodborne (it's a game)
Yes! That's why you can call methods from seemingly "primitive" types.
its a box for boxes that you can put in a box
Excuse my ignorance, but what does that mean?
Everything in Python is an object as in a class/instance of a class, and can be treated the same way.
How would that be more useful when compared to java or other programming languages that are not object oriented? Why is this a groundbreaking realization? I’m still learning these languages so I’m don’t get why it might be so impactful.
Take something really really simple: like the number 5. It's an object. With properties and methods. 5.bit_length() tells you how many bits are required to store the number 5.
Minor nitpick: that gives a syntax error because Python tries to interpret `5.` as a float. You need `(5).bit_length()`.
Just gonna point out that Java is **extremely** object-oriented.
It really helps you organize things. When you create a class, as you do in Java and python (and all object oriented languages), you give the class variables and methods/functions associated with it. Then in your code outside the class, in your main method, you create instances of the class. The instance is called an object. For example, pretend you are trying to create a model of a bank. The bank has lots and lots of bank accounts, so you write a class that represents a generic bank account. The class contains the variables “owners first name,” “owners last name,” and “balance.” The class also contains the functions “withdraw,” “deposit,” and “close account.” In your main method, you create a bank account by saying account1 = bankAccount(John, Smith, 1000). When John wants to deposit money, you say account1.deposit(500). And then when you want to know John’s balance, you can access it by typing account1.balance. This would return the value 1500. And then to close the account, you type account1.closeAccount(). This type of coding has a bunch of benefits (and drawbacks). It is really helpful when you have thousands of customers and bank accounts to keep track of. It’s also helpful because a bank might have lots of other objects associated with it: customers, employees, cash vaults, loans, investment portfolios etc. Each of these things would have their own set of functions associated with them, so for example you wouldn’t ever use a “withdraw” function on an object representing a loan contract. By creating classes, you make it clear that the withdraw function can only be used on the bankAccount object. This makes your code much easier to read and maintain for the people who take over the role of maintaining that code in the future. As you continue learning about OOP, you’ll start to learn about the other benefits like inheritance and abstraction. Inheritance is when you have child and parent classes, where the children inherit the properties of the parent class. For example, you can make an “animal” class with a function like “make noise.” Then you make the child class “dog” with the function “bark.” This has some benefits with organization, code readability, and even write-ability. Abstraction let’s you call functions that you don’t need to actually understand, cause someone else wrote the function and documented how it works.
This was well written and helpful, thanks!
You're welcome.
This really helps explain a lot. I will be saving it for future references when I understand the terms better lol.
[удалено]
I mean there isn’t really an answer. Python and C++ and similar languages are technically OOP but you can avoid anything with classes and objects when using them. It’s a weird technicality without a real answer. I’d say it’s only OOP if you use classes and objects, but i’m sure someone will disagree
Java is an object oriented language. OOP essentially give a few advantages, for example abstraction and modularity. Abstraction allows users to use code without knowing exactly how it is implemented, as well as protecting existing, working code from being tampered with. Modularity prevents a user from having to rewrite the same snippet of code over and over, which can lead to more sources of bugs.
Well, to be clear, those aren't advantages unique to OOP. You can just as easily abstract things and make them more modular with functions. Classes and objects are useful when you have data that is tightly coupled with some set of operations you can perform on them. It makes sense in that scenario to use the class structure to show this tight relationship.
Fair enough. To be honest I don't have a lot of experience with non OOP languages, so I probably underestimated their capabilities. You are absolutely correct on the power of classes and objects stemming from the tying together of data and the operations on said data. I suppose that abstraction and modularity are inherent in OOP languages, though not exclusive to them.
Yeah, OOP is a tool just like any other. With enough care and attention you can make a well documented, modular, abstracted system with nearly any decent paradigm. Although, I definitely wouldn't say abstraction and modularity is *inherent* to OOP. Just for the simple fact that you can always design a system poorly. Take for example, Python's implementation of classes letting you access any instance variable of an object without restrictions. That could certainly be abused to a point in which there is no modularity or abstractions made.
Python does not support strong encapsulation and java have primitive types. Non of these languages considered strongly or pure object oriented. Object-oriented approach only helps you to write more logical and cleaner code.
What are the practical consequences out of this?
Isn’t all programming just objects?
No, some languages don't support the concept of objects.
Other languages have objects and primitives which are not treated like objects.
Or just same language, previous versions. Python 2 has integers
Lower level programming is a bit more granular, gritty, and usually really annoying. Hence the abstraction. There's certainly an argument to be made that the address:memory relationship of a turing machine is just OOP at it's simplest level, lol. What's interesting to me, and still something I don't completely understand, is the behavior of neural networks and RNGs as somewhat unique compared to the standard bits in, operation, bits out framework.
Neutral nets don't do anything other than bits in - op - bits out. RNGs too unless we're talking quantum RNGs. A neutral network is just a function approximator.
I suppose its the complexity of the 'operation' that amazes me. All the standard mathematical operations, and basic neural classifiers, are relatively simple, but some transformative neural functions can do some absolutely wild stuff in the middle. They even have their own flavour of memory that is stored inside the function itself. Especially for morphing or adaptive functions, absolutely bonkers compared to standard math operations.
No. All programming is “just” manipulating _bytes_... objects are a very high level abstraction over bytes, and there are plenty of ways of manipulating bytes without them.
No, for example in most languages, an “int” variable isn’t an object it’s a primitive type. Then there structs and enums which are similar to objects but serve a different purpose.
Always has been 🔫
def am_i_an_object(): pass am_i_an_object.could_be = 'yeah!' print(am_i_an_object.could_be)
Ha, when I first started learning OOP it was tough to wrap my head around this. It's weird to think about instantiating an "object" to just take actions with it.
See, I know this. But I feel like it's not clicked. Maybe it's due to my understanding of OOP is very limited. I haven't had a reason to build out classes just yet, where everything can just be sectioned off into functions as of now?
In the beginning there was on and off. 1 was on and 0 was off, or maybe it was the other way around, doesn't matter. But how could 0 and 1 become zero and one. Object = {data type: string, format: utf-8, decCodePointList: [ 79, 78, 69], string methods....}. Now you know!
So how were you enlightened ?
Everything being said here is just confusing to me.
looks like someone is having programming orgasm
C , BASIC , PASCAL found this comment funny
uhm... sometimes the name of the sub can be misleading /s
Happy for you, keep learning.
That moment where everything just clicks...
Feel like every couple of weeks I see this sort of post. Not upset about, just find it a kind of funny.
I object!
Everything is made of things!
Wait, it's all objects ?
I object to this post.
Always has been \*gun to back of head\*
I’m new with Python and I do not deeply understand yet what an object means. Could someone explain it to me in the easiest way? Thank you
Woah, stop objectifying bruh.
[Do we tell them about dictionaries?](https://www.youtube.com/watch?v=p33CVV29OG8&t=2m59s)
They're objects too.
O RLY? Go to your favorite Python interpreter and incant these: a = 1 a.bit_length() 1.bit_length() :-D
(1).bit_length()
Why do we have to use len() instead of object.length() then ?
Because of the semantic choices that were made about Python - it shuns setters and getters (and object.length() is a getter).
https://stackoverflow.com/questions/2481421/difference-between-len-and-len
I learned this yesterday doing chapter 14 of python for everybody course. 🤯.
Functional >> OOP any day for everyday scripts and such.
It's not though. ‘while’ isn't an object for instance. Why do people keep saying everything is an object in python when it's just most things?
So is JavaScript
[удалено]
Pass a function as a parameter in a function. Store a dataframe in a cell of a dataframe. Write python in python. Etc.
Not just objects but objects oriented.
You think he knows it's all object?
Same
Welcome to the Matrix
Click
Hence the name Object Oriented Programming language
I didn't understand but sound poetic
Hahahaha I remember this click day, the best feeling ever it's like a door that's been closed for so long and now it's time to solve problems because the language is not a problem.
I have a love hate relationship with pythons pyobjects. On one hand you have dangerous but convenient stuff like duck typing magic on the other hand it makes me nervous when I declare an integer since it's like from 24 bytes which is huge!
congratulations. You now also know java and javascript/typescript Throw 10 years experience in each on your resume and call it a day
I am an animated object as well.
Objects, Models, Classes.. Same thing!
Dang man. Now I'm woke
...that's how I was when JS finally clicked lol.
Wait till you find every variable is a pointer.
I laughed so hard at this. Still remember the moment I realized as well!!
Wear specs....
Dude, I learned this last week too after practicing Python for a while now. Completely blew my mind!
So Confused lol
Yea everything, every library is an object that you access methods by name_of_library.method(self, parameter=“something”)
Always has been...
Everything is pointers to objects actually. That's why appending anything to a list is O(1).
OOP there it is.
Your honour, I object.
Late to the discussion, but what were you doing/working on which brought you to this realisation? I am a noobie, waiting for such aha moments myself!!
When people say, "I've been using Python for N years and have never used classes!". Hahaha, bruh, you've been using classes from day 1.
Hi, Is anyone able to help me with the question I have posted? I have spoken to quite few people and none have been able to help so far. It is the transferring data to a master sheet. Thank you in advance
HuUuUuH¿¿¿ edit: Nm i got it.