Skip to main content
Stack Overflow
  1. About
  2. For Teams

Return to Revisions

1 of 4
AlokThakur
  • 3.8k
  • 1
  • 21
  • 33

Class attributes- are everything listed in the class Classname: code block, It can be above or below of any function.

Instance attribute - which is created by using instance.attr or self.attr(here self is instance object only)

class Base:
 cls_var = "class attribute"
 def __init__(self):
 self.var = "instance attribute"
 def method(self):
 self.var1 = "another instance attribute"
 cls_var1 = "another class attribute"

Class attributes and instance objects - You can consider class object as a parent of all of its instance objects. So instance object can access attribute of class object but any thing defined under class body is only class attribute.

class Base:
 cls_var = "class attribute"
 def __init__(self):
 self.var = "instance attribute"
b = Base()
print b.var                           # it should print "instance attribute"
print b.cls_var                     # it should print "class attribute"
print Base.cls_var                 # it should print "class attribute"
b.cls_var = "instance attribute"
print Base.cls_var # it should print "class attribute"
print b.cls_var # it should print "instance attribute"
AlokThakur
  • 3.8k
  • 1
  • 21
  • 33

AltStyle によって変換されたページ (->オリジナル) /