0

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

3
  • The __init__ function is your constructor, so it increments counter whenever you create a new `Employee object. What exactly are you asking? Commented Mar 31, 2017 at 14:06
  • The code you've shown won't run. counter should be accessed via the instance or class Commented Mar 31, 2017 at 14:07
  • @MosesKoledoye: Why not? Oh, I see now... counter += 1 should be Employee.counter += 1. Commented Mar 31, 2017 at 14:07

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, I forgot to put the Employee.counter += 1 . So basically since there is now reference , the garbage collector will free the heap. Thank you for theexplanation.
1
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.