# Python object and class

To assign one class(template) to an object you would do the following:

```python
class MyClass(object):
    variable = "blah"

    def function(self):
        print("This is a message inside the class.")

myobjectx = MyClass()
```

**Now the variable "myobjectx" holds an object of the class "MyClass"** that contains the variable and the function defined within the class called "MyClass".

You can create multiple different objects that are of the same class(have the same variables and functions defined). However, **each object contains independent copies of the variables** defined in the class.

### Why does new class need to inherit from "object"? Do we have to do it?

In short, it's about "old vs new style python objects".

**In Python 3,** apart from compatibility between Python 2 and 3, inheriting it or not makes no difference. **But in Python 2**, there are some perks for inheriting it.

**In Python 2.x** (from 2.2 onwards) there's two styles of classes depending on the presence or absence of `object` as a base-class:

* classic style: no inheriting
* new style: inheriting a build-in type, object, as a base class. Using new style has some perks:
  * classmethod
  * staticmethod
  * properties with property: Create functions for managing the getting, setting and deleting of an attribute.
  * \_\_slots\_\_: Saves memory consumptions of a class and also results in faster attribute access.
  * The [`__new__`](https://docs.python.org/3/reference/datamodel.html#object.__new__) static method: lets you customize how new class instances are created.
  * [Method resolution order (MRO)](https://www.python.org/download/releases/2.3/mro/): in what order the base classes of a class will be searched when trying to resolve which method to call.
  * Related to MRO, [`super` calls](https://docs.python.org/3/library/functions.html#super). Also see, [`super()` considered super.](https://rhettinger.wordpress.com/2011/05/26/super-considered-super/)

One of the downsides of new-style classes is that the class itself is more memory demanding. Unless you're creating many class objects, though, this might just be an issue and it's a negative sinking in a sea of positives.

**In Python 3.x**, things are simplified. Only new-style classes exist (referred to plainly as classes) so, the only difference in adding `object` is requiring you to type in 8 more characters.

**In summary**, what should we do? **In Python 2:** _always inherit from `object` explicitly_. Get the perks. **In Python 3:** inherit from `object` if you are writing code that tries to be Python agnostic, that is, it needs to work both in Python 2 and in Python 3. Otherwise don't, it really makes no difference since Python inserts it for you behind the scenes.

{% embed url="https://www.learnpython.org/en/Classes_and_Objects" %}

{% embed url="https://stackoverflow.com/questions/4015417/python-class-inherits-object" %}
