Class and instance attributes

Class Attribute vs. Instance Attribute

  • An instance attribute is a Python variable belonging to one, and only one, object. This variable is only accessible in the scope of this object and it is defined inside the constructor function, __init__(self,..) of the class.
  • A class attribute is a Python variable that belongs to a class rather than a particular object. It is shared between all the objects of this class and it is defined outside the constructor function, __init__(self,...), of the class.

__dict__

  1. The class is made up of attributes(data) and methods(functions).
  2. Attributes and methods are simply defined as normal variables and functions.
  3. As noted in the corresponding docstring, the __init__() method is called the initializer . It’s equivalent to the constructor in other object oriented languages, and is the method that is first run when you create a new object, or new instance of the class.
  4. Attributes that aply to the whole class are defined first, and are called class attributes.
  5. Attributes that aply to a specific instance of a class (an object) are called instance attributes. They are generally defined __init__(); this is not necessary, but it is recomended (since attributes defined outside of __init__() run the risk of being accessed before they are defined).
  6. Every method , include in the class definition passes the object in question as its first parameter. The word self is used for this parameter (usage of self is actually by convention, as the word self has no inherent meaning in Python, but this is one of Python’s most respected conventions, and you should always follow it).
  7. Some of the class’s methods have the following form: __FunctionName__(self, other stuff). All such methods are called “Magic methods ” and are important part of classes in Python.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store