Timeline for Class methods/instance methods in Python
Current License: CC BY-SA 3.0
13 events
| when toggle format | what | by | license | comment | |
|---|---|---|---|---|---|
| Oct 14, 2013 at 21:25 | vote | accept | David | ||
| Oct 14, 2013 at 21:23 | comment | added | Bi Rico |
You can also use type(self).employeeCount instead of self.__class__.employeeCount
|
|
| Oct 14, 2013 at 21:17 | comment | added | Daniel Roseman |
You can access it through the instance, but if you modify it in any way (eg david.employeeCount += 1 you'll actually create an instance attribute that shadows the class one, and the changes won't reflect in the class variable. In __init__, you'll need to explicitly access the class: self.__class__.employeeCount += 1 should work.
|
|
| Oct 14, 2013 at 21:00 | comment | added | David | Further, it seems I could do david.employeeCount, and it will still be seen, but that doesn't seem to make any sense. Will this always be a side-effect? (sorry for all the questions) – | |
| Oct 14, 2013 at 20:59 | comment | added | David | I get an error though, in my initialize method when I try to increment the employeeCount. How would I get past that? | |
| Oct 14, 2013 at 20:53 | comment | added | Daniel Roseman | Yes, that's exactly what it does. | |
| Oct 14, 2013 at 20:49 | comment | added | David |
How would I access it in a method then? Is your way of making a class method going to have cls.employeeCount point to employeeCount?
|
|
| Oct 14, 2013 at 20:46 | history | edited | Daniel Roseman | CC BY-SA 3.0 |
added 6 characters in body
|
| Oct 14, 2013 at 20:46 | comment | added | Daniel Roseman | No, defining it that way is fine, that doesn't give an error. It's accessing it inside a method that will give an error. | |
| Oct 14, 2013 at 20:46 | comment | added | Daniel Roseman | Nothing, because it doesn't work: you'd get "TypeError: unbound method get_employee_count() must be called with Employee instance as first argument (got nothing instead)" in Python 3, and "global name 'employeeCount' is not defined" in Python 2. | |
| Oct 14, 2013 at 20:46 | comment | added | David |
Furthermore, how would I create a class variable in Python? Evidently, employeeCount = 0 would generate an error.
|
|
| Oct 14, 2013 at 20:42 | comment | added | David |
Interesting. Then, in my example, what exactly would you call get_employee_count()?
|
|
| Oct 14, 2013 at 20:39 | history | answered | Daniel Roseman | CC BY-SA 3.0 |