HOW OBJECT AND CLASS ATTRIBUTES WORK.


Class attributes:

Class attributes are defined outside a method in the class definition and are shared by all class instances.
It can also be easily modified by just reassigning a value.

Example in code:

#define the class
class Car:
        #showing class attribute
        wheels = 4
        #updating class attribute
        wheels = 5

This makes it a class attribute because it's outside a method in the class.

Instance attributes:

Instance attributes are defined inside the "__init__" method of Python and are specific to each instance.

Example in code:

#define the class
class Car:
        #init method
        def __init__(self, wheels):
                self.__wheels = wheels

This makes it an instance attribute because it is defined inside Python's "__init__" method.

Ways to create them:

Class:

Define them in the class body

Instance:

Define them in the "__init"" method or "def __init__(self, ...)"

Differences:

  • Class attributes are shared in all instances of the class, while instance attributes are unique to each other.

  • Class attributes are accessed using the class name, while instance attributes are accessed using the instance itself.
Advantages and Disadvantages:

Class:

Class attributes are memory efficient as they are shared among instances but lack instance specification and customization.

Instance:

Instance attributes are now memory efficient as they use more memory as each instance stores its set of attributes but allows instance specification and customization.

Python handling of object and class attributes using "__dict__" :

"__dict__" is a dictionary that has instance attributes and their values. It also holds attributes and methods in class attributes.

Comments

Popular posts from this blog

IMMUTABLES AND MUTABLES IN PYTHON