Class Attributes, Instance Attributes And Local Variables
· Def:-
Its very important to understand the structure of attributes and variables in a class. As, many times it can be misleading
and makes the code inefficient and confusing.
· Code:-
class Foo(object):
# class attribute
bar = 1
def __init__(self):
# instance attribute
self.bar = 2
# Local variable to __init__ method
# shadowing the class attribute bar
bar = 3
print '''Local Variable:-
Name:- bar
Id:- {0}
Value:- {1}'''.format(id(bar), bar)
inst_foo = Foo()
print '''Class Attribute:-
Name:- bar
Id:- {0}
Value:- {1}'''.format(id(Foo.bar), Foo.bar)
print '''Instance Attribute:-
Name:- bar
Id:- {0}
Value:- {1}'''.format(id(inst_foo.bar), inst_foo.bar)
· Result:-
Local Variable:-
Name:- bar
Id:- 5540904
Value:- 3
Class Attribute:-
Name:- bar
Id:- 5540928
Value:- 1
Instance Attribute:-
Name:- bar
Id:- 5540916
Value:- 2
· Tip:-
· The class attributes are different from instance attributes for a particular class even if they have the same name.
· Local variables are different from class attributes as well as from instance attributes for a class.
Moreover, local variables shadows(as they do for global variables too) the class attributes in a particular scope.
HTML Comment Box is loading comments...