I am new to Python, and I have one dilemma concerning OOP (I am familiar with OOP concepts).
Basically, I have a class with a static class-variable (counter that shows how many objects I have instantiated):
class Employee:
counter=0
def __init__(self,name):
self.name=name
Employee.counter+=1
So now I instantiate an object:
obj1=Employee("Alan")
My question is: what happens when I have this call? What happens behind, because the static variable "counter" is incremented, but it is possible to access the object created like this?
Employee("foo")
<__main__.Employee object at 0x02A16870>
Thanks
2 Answers 2
First of all, you need counter+=1 to be Employee.counter += 1 in order for the code to behave like you say it does. Otherwise you will get an error for trying to increment a variable that's not known within the scope of __init__.
Since you have no reference to Employee("foo") it will soon be garbage collected and gone forever. However, this does not change the fact that Employee.__init__ was called to increment your counter.
1 Comment
Employee("foo")
This object created above will be lost as soon as it is used and cannot be re-used whereas when you instantiate an object like
obj1=Employee("Alan")
you have a reference of that object in obj1 and it can be re-used.
My question what happens when I have this call? What happens behind
The __init__ function is the constructor and it is called each time you create a new object of your class. As this __init__ function increments the counter variable, so each time an object is created, __init__ function is called and counter gets incremented.
__init__function is your constructor, so it incrementscounterwhenever you create a new `Employee object. What exactly are you asking?countershould be accessed via the instance or classcounter += 1should beEmployee.counter += 1.