Reputation: 149
I know this is a noob question but I am learning OOPs and can't able to figure the outputs got
This is the code I found and may i know how this runs?
class InstanceCounter(object):
count = 0
def __init__(self, val):
self.val = val
InstanceCounter.count += 1
def set_val(self, newval):
self.val = newval
def get_val(self):
print(self.val)
def get_count(self):
print(InstanceCounter.count)
a = InstanceCounter(5)
b = InstanceCounter(10)
c = InstanceCounter(15)
for obj in (a, b, c):
print("value of obj: %s" % obj.get_val())
print("Count : %s" % obj.get_count())
Upvotes: 0
Views: 134
Reputation: 1891
You have a class called InstanceCounter
which inherits from object
. The inherince from object
can be removed if you use Python3
. This class has an attribute count
and value
and some methods
(functions - for example set_val
).
Now you create three objects of your class and set the value of value
to 5
, 10
and 15
by passing these values into the constructor. You also increase the static attribute (see here) count
by one with each constructor call. A static attribute is used with the notation Class.Attribute
.
In the last step you loop over a list of your three objects ((a, b, c)
) and store each of this object in the object obj
, so obj
will represent a
then b
and then c
. So you can call the methods of this object, because your object obj
has the type InstanceCounter
and so obj
contain the same methods and attributes.
By the way I have reworked your code so make it more understandable and use Python3
syntax.
class InstanceCounter:
count = 0
def __init__(self, val):
self.val = val
InstanceCounter.count += 1
def set_val(self, newval):
self.val = newval
def get_val(self):
return self.val
def get_count(self):
return InstanceCounter.count
a = InstanceCounter(5)
print("Count : {}".format(a.get_count()))
b = InstanceCounter(10)
print("Count : {}".format(b.get_count()))
c = InstanceCounter(15)
print("Count : {}".format(c.get_count()))
for obj in (a, b, c):
print("value of obj: {}".format(obj.get_val()))
print("Count : {}".format(obj.get_count()))
This result in the following output:
Count : 1
Count : 2
Count : 3
value of obj: 5
Count : 3
value of obj: 10
Count : 3
value of obj: 15
Count : 3
For a better understanding of static attributes:
So if you have three objects with type InstanceCounter
you have three different attributes with name val
because each object with type InstanceCounter
contains one attribute val
- an instance attribute
and one identical attribute with name count
- a class attribute
.
count
is a class attribute
for the class InstanceCounter
. This
attribute has the same value for all objects with type
InstanceCounter
. Used with Classname.Attributename
- for example InstanceCounter.count
.val
is a instance attribute
because each instance of a class InstanceCounter
has his own value. Used with Instancename.Attributename
- for example a.val
.See here for more information.
Upvotes: 3