Everything is an object
An object is a fundamental building block of an object-oriented language. Integers, strings, floating point numbers, even arrays and dictionaries, are all objects. More specifically, any single integer or any single string is an object. The number 12 is an object, the string "hello, world" is an object, a list is an object that can hold other objects, and so on. You've been using objects all along and may not even realize it.
Objects have types
Every object has a type, and that type defines what you can do with the object. For example, the int type defines what happens when you add something to an int, what happens when you try to convert it to a string, and so on.
Conceptually, if not literally, another word for type is class. When you define a class, you are in essence defining your own type. Just like 12 is an instance of an integer, and "hello world" is an instance of a string, you can create your own custom type and then create instances of that type. Each instance is an object.
Classes are just custom types
Most programs that go beyond just printing a string on the display need to manage something more than just numbers and strings. For example, you might be writing a program that manipulates pictures, like photoshop. Or, perhaps you're creating a competitor to iTunes and need to manipulate songs and collections of songs. Or maybe you are writing a program to manage recipes.
A single picture, a single song, or a single recipe are each an object of a particular type. The only difference is, instead of your object being a type provided by the language (eg: integers, strings, etc), it is something you define yourself.
Answer from Bryan Oakley on Stack OverflowWhat exactly is an object in Python?
What is meant by "everything in python is an object"
Can Someone Explain Objected Oriented Programming In Python Like I'm an Idiot?
There's a massive Wikipedia page on OOP that will give you every little gritty detail. And, there are a lot of OOP evangelists and an ever increasing amount of OOP cynics. Either of which will try to sell you benefits of Language-X, and why Language-Z is the greatest invention since the wheel. Including these 30,000 words of rhetoric, fallacies, and pure garbage.
Here is everything you need to know about OOP. There are three features that make a language an OO language. Any language can have one or two of the features and not be OO, but any language that has all three can be considered OO. They are:
-
Encapsulation
-
Inheritance
-
Polymorphism
Encapsulation is a feature that allows for a data structure to be associated with a set of methods*; An object. In a language without encapsulation, like C, then you will have libraries of functions* and each piece of data is passed to a function. In a language with OO, like Python, you can define a Class that, when instantiated, creates an object. That object, usually, is an aggregate datatype with added logic, methods*. Each instance method has an implicit argument, typically, named self.
* A note on the terms "method" and "function". They're both just synonymous with "subroutine" or a sequence of instructions. However, most programmers differentiate them. A "subroutine" is blockless piece of code that must be reached by a goto statement. A "function" is a block of code that operates exclusively on it's arguments. And, a "method" is a block of code that is associated with an object.
Most languages have generic base "types" like strings, integers, floats, and arrays. When have a need for a "type" with several associated values, then you need an 'aggregated data type'. In a language without Encapsulation, the term is usually called a "struct". With Encapsulation, a "type" is nearly synonymous with a "class" and an instance is called an "object". There's, also, a spectrum of OO-ness. Java base types are NOT objects. An int in Java is not an object, it is a type, but an Integer is an object. In Python everything is an object.
A crude example in Python would be:
class Greeter(object):
def __init__(self, phrase):
self.phrase = phrase
def greet(self, name):
print(self.phrase.format(name))
hello_greeter = Greeter("Hello, {}!")
hello_greeter.greet("Ms. Smith")
In the above example, we see our first hint of Inheritance. The Greeter class inherits from object (Note: (object) is implicit in Python3.) Inheritance is the ability to associate and expand on another class's data structure and functionality. We could very easily create a HelloWorldGreeter from Greeter.
class HelloWorldGreeter(Greeter):
def __init__(self):
super(HelloWorldGreeter, self).__init__("Hello, {}!")
def greet(self):
super(HelloWorldGreeter, self).greet("World")
In the Inheritance realm there is single-inheritance and multiple-inheritance. The HelloWorldGreeter is an example of a class with single-inheritance. In fact, must OO languages are specifically only single-inheritance. However, I mention it here because Python isn't most languages as it allows for multiple-inheritance. Which is the reason for the very explicit super(...) function. This function is able to solve the "diamond problem" which is an issue about how inheritance is ordered. I'll just stop here because it's a lengthy topic in itself; follow the link to Wikipedia for more. If you want to know more Python's super(...) method, then read Raymond Hettinger's post "Python's super() considered super!"
A lot of detractors consider inheritance -- especially, multiple inheritance -- as a complicated obfuscation that makes code harder to debug.
That leaves us with Polymorphism. This will be the most difficult for me to explain and, I suspect, the most contentious of OO features. And, it's going to require us to take a step back.
All languages have a "type system". There are a few adjectives that get thrown around. The two that most people confuse (and I might do so myself) are the mutually exclusive "weakly" (or "loosely") typed and "strongly" typed languages. Also, there are other concepts that are frequently confused as 'strong' and 'weak' which are "static type-checking" and "dynamic type-checking". To unravel all of this, here is the best I can do to concisely describe these concepts:
-
Strongly Typed: A strongly typed language is one that will cause an error if a piece of logic tries to operate on an unexpected type. Something that tends to confuse a lot of people is the fact that Python (and Ruby) are strongly typed. I'll try to explain later in 'Dynamic Type-Checking'.
-
Weakly Typed: A language that attempts to perform type conversion would be considered "weakly" typed. Java, for instance, does "auto-boxing" and "auto-unboxing" for it's basic types; ex
int fortytwo = 20 + new Integer(22). In C, one can add pointers to numeric types and numeric types can be coerced into another numeric types; ex. anintcan safely converted tolong. -
Static Type-Checking: A static type-checking language is one that tracks each object's type to prevent type-specifc logic errors. For example, one shouldn't pass a string to a function that expects to receive two integers. Typically, this is a compile time feature which gives an added performance benefit because the resulting program does not need runtime type checking.
However, languages like javascript and Python (PEP 484) are adding "type hinting" which can be thought of as "unenforced static type-checking". Rather than halting compilation, errors and warnings will be presented.
-
Dynamic Type-Checking: A dynamic type-checking language is one that does not make any attempt to protect the program for logic errors based on object type. That is to say, type checking must be done at runtime through language-specific functionality. For example, if one wanted to run a specific function on an object, then one might want to be certain that the object provides that functionality or, else, risk a runtime error. This is commonly known as "duck typing"; Coming from the common phrase, 'If it walks like a duck and quacks like a duck, then it is a duck'.
Okay. Back to Polymorphism. A language is considered polymorphic if an object can be treated as its own specific type or any of the inherited types, or "subtypes". A quick example just to wrap this up (because I've written way to much):
class Vehicle(object):
pass
class Truck(Vehicle):
pass
class Car(Vehicle):
pass
isinstance(Car(), Car) # True
isinstance(Truck(), Car) # False
isinstance(Car(), Vehicle) # True
isinstance(Truck(), Vehicle) # TrueHope it helps.
More on reddit.comExplain it to me like I'm Five: Classes + __init__ function
Classes are data encapsulated with structure and behaviour. You use them when you have similar things that all behave the same way or all share meaning.
If you had a Dog class, well, all Dogs have a name, breed, colour, and all Dogs have the same behavior, barking, wagging, running.
The __init__ method is the constructor. This method is called when the object is created. You use it to set up the initial state of the object. When a Dog is created it 'gets' a name, breed and colour.
For a real programming example, say you are making a shooter game. In this game you can equip many different weapons which have different characteristics but all function more or less the same way. You could make a Weapon class which has data like ammunition capacity, bullets remaining, or damage done. Then you could make this class have a shoot() method and when the user presses a button when playing the game it calls this method. Inside the method it checks to see if there is ammunition remaining in the magazine, and if so, removes a bullet from the magazine. And if the user needs to reload you can make a reload() method which checks how much ammunition the player has, and if there is enough left, refills the magazine and removes the bullets from the ammunition pile.
Then you can take this class and make many child classes all with different properties and maybe with additional behaviour, but still basicaly function the same as every other weapon.
More on reddit.comVideos
Everything is an object
An object is a fundamental building block of an object-oriented language. Integers, strings, floating point numbers, even arrays and dictionaries, are all objects. More specifically, any single integer or any single string is an object. The number 12 is an object, the string "hello, world" is an object, a list is an object that can hold other objects, and so on. You've been using objects all along and may not even realize it.
Objects have types
Every object has a type, and that type defines what you can do with the object. For example, the int type defines what happens when you add something to an int, what happens when you try to convert it to a string, and so on.
Conceptually, if not literally, another word for type is class. When you define a class, you are in essence defining your own type. Just like 12 is an instance of an integer, and "hello world" is an instance of a string, you can create your own custom type and then create instances of that type. Each instance is an object.
Classes are just custom types
Most programs that go beyond just printing a string on the display need to manage something more than just numbers and strings. For example, you might be writing a program that manipulates pictures, like photoshop. Or, perhaps you're creating a competitor to iTunes and need to manipulate songs and collections of songs. Or maybe you are writing a program to manage recipes.
A single picture, a single song, or a single recipe are each an object of a particular type. The only difference is, instead of your object being a type provided by the language (eg: integers, strings, etc), it is something you define yourself.
To go deep, you need to understand the Python data model.
But if you want a glossy stackoverflow cheat sheet, let's start with a dictionary. (In order to avoid circular definitions, let's just agree that at a minimum, a dictionary is a mapping of keys to values. In this case, we can even say the keys are definitely strings.)
def some_method():
return 'hello world'
some_dictionary = {
"a_data_key": "a value",
"a_method_key": some_method,
}
An object, then, is such a mapping, with some additional syntactic sugar that allows you to access the "keys" using dot notation.
Now, there's a lot more to it than that. (In fact, if you want to understand this beyond python, I recommend The Art of the Metaobject Protocol.) You have to follow up with "but what is an instance?" and "how can you do things like iterate on entries in a dictionary like that?" and "what's a type system"? Some of this is addressed in Skam's fine answer.
We can talk about the python dunder methods, and how they are basically a protocol to implementing native behaviors like sized (things with length), comparable types (x < y), iterable types, etc.
But since the question is basically PhD-level broad, I think I'll leave my answer terribly reductive and see if you want to constrain the question.
Thinkpython book by Allen Downey defines objects as something a variable can refer to to which he adds "object" and "value" can be used interchangeably. So, if my understanding serves me well, a variable stores a value, for e.g. x = 5, does that imply 5 is an object as well?
Then, I come across "file object" which is known to bear reference to a file. Maybe I'm overcomplicating things that's why I can't seem to grasp these concepts.