Python how Object and class attributs work how they Works
lets define an empty class called Dog:
Classes contain characteristics called?Attributes. We make a distinction between?instance attributes?and?class attributes.
Instance Attributes?are unique to each object, (an instance is another name for an object). Here, any?Dog?object we create will be able to store its name and age. We can change either attribute of either dog, without affecting any other dog objects we’ve created.
This?__init__?is called the?initializer. It is automatically called when we instantiate the class. It’s job is to make sure the class has any attributes it needs. It’s sometimes also used to make sure that the object is in a valid state when it’s instantiated, like making sure the user didn’t enter a negative age for the dog.
We have to include the?self?parameter so that our initializer has a reference to the new object being instantiated.
Class Attributes?are unique to each class. Each instance of the class will have this attribute. It’s sometimes used to specify a defualt value that all objects should have after they’ve been instantiated. Here, our class attribute is species
Class attributes?are the variables defined directly in the class that are shared by all objects of the class.
Instance attributes?are attributes or properties attached to an instance of a class. Instance attributes are defined in the constructor.
The following table lists the difference between class attribute and instance attribute :
__dict__
Dictionary
Dictionaries are used to store data values in key:value pairs.
A dictionary is a collection which is ordered*, changeable and do not allow duplicates.