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, throwing an error otherwise).

How class attributes handle Assignment

  • Instance namespace mainly under def __init__(self, x)
    foo = MyClass(2) foo.class_var ## 1 MyClass.class_var = 2 foo.class_var ## 2
  • If a Paython class variable is set by accessing an instance, it will override the value only for that instance. This essentially overrides the class variable and turns it into an instance variable available, intuitively, only for that instance. For example: foo = MyClass(2) foo.class_var ## 1 foo.class_var = 2 foo.class_var ## 2 MyClass.class_var ## 1
  • Do not use mutable variables in class attributes

When to use class attributes

  • storing constants.
  • Define default values.
  • Tracking all data across all instances of a given class.
  • class Person(object): all_names = [] def __init__(self, name): self.name = name Person.all_names.append(name) joe = Person('Joe') bob = Person('Bob') print Person.all_names ## ['Joe', 'Bob']
Under-the-hood class attr

Comments

Popular posts from this blog

Object detection

Common Words