Posts

Showing posts from October, 2019

Python class attributes and Python instance attributes.

A python class attribute is an attribute of the class, rather than an attribute of an instance of the class. Here is an example: class MyClass: # Depending the context # Access as local variable. class_att = 1 def __init__(self, x, y): # Depending on the context # access using dot syntax. self.x = x self.y = y inst1 = MyClass(1, 2) inst2 = MyClass(3,4) inst1.class_att inst2.class_att MyClass.att class vs instance namespace A namespace is a mapping from name to objects, with the property that there is zero relation ship between variables in different namespaces. class and instance have their own namespace. MyClass.__dict__ is different from inst.__dict__ . When you try to access an attribute inside one instance.lass, it first looks at its instance namespace. If it finds the attribute, it returns the associated value. If not, it then looks in the class namespace and returns the attribute (if it’s present, throw...