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

Return to Revisions

3 of 4
added 543 characters in body
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 method.

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.However any thing defined under class body is class attribute only.

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"

Instance Method - Method which is created by def statement inside class body and instance method is a Method which first argument will be instance object(self). But all instance methods are class attributes, You can access it via instance object because instances are child of class object.

>>> class Base:
 def ins_method(self):
 pass
 
>>> b = Base()
>>> Base.__dict__
{'__module__': '__main__', '__doc__': None, 'ins_method': <function ins_method at 0x01CEE930>}
>>> b.__dict__
{}

You can access instance method by using class object by passing instance as it's first parameter-

Base.ins_method(Base())

You can refer these two articles written by me on same topic and post me your query - http://www.pythonabc.com/python-class-easy-way-understand-python-class/ http://www.pythonabc.com/instance-method-static-method-and-class-method/

AlokThakur
  • 3.8k
  • 1
  • 21
  • 33

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