1

in a code example on this site i saw the following code example:

class Robot:
    __counter = 0
    
    def __init__(self):
        type(self).__counter += 1
        
    def RobotInstances():
        return Robot.__counter
    

The __init__ method in the example above is incrementing the __counter whenever the class is instantiated.

My question is: Since type(self) is supposed to return the type of an object, can it also be assigned to?

E_net4
  • 27,810
  • 13
  • 101
  • 139
Dror
  • 5,107
  • 3
  • 27
  • 45
  • 1
    `type(self)` returns the type of `self`. i.e. the class. – juanpa.arrivillaga Oct 28 '21 at 07:26
  • 1
    WRT (3), did you try and see? – juanpa.arrivillaga Oct 28 '21 at 07:26
  • __counter in this example is a class variable rather than an instance variable. Are you familiar with the difference? – ScienceSnake Oct 28 '21 at 07:27
  • `type(self)` will return `Robot`, so you're assigning to `Robot.__counter`. Assigning to `self.__counter` would create an individual instance variable for each instance. – deceze Oct 28 '21 at 07:27
  • 3
    "since type(self) is supposed to return the type of an object, how can it be the target of an assignment ?" it isn't, this is attribute assignment. Just like any other object, `my_object.some_attribute += 1` increments that attribute on that object (if it exists, otherwise, it throws an Attribute Error). Types/classes are like any other object, they are *instances* of `type`, which is itself a class/type, a *metaclass* – juanpa.arrivillaga Oct 28 '21 at 07:32
  • 1
    Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackoverflow.com/rooms/238638/discussion-on-question-by-dror-unclear-python-instance-method-increments-type). – deceze Oct 28 '21 at 07:48
  • 2
    You're *not* "assigning to the type of an object". You're assigning to the attribute `__counter` of the object returned by `type(self)`. And in this example, `type(self)` is the same as `Robot`. – deceze Oct 28 '21 at 09:38
  • "since type(self) is supposed to return the type of an object, can it also be assigned to ?" You can just try that. (Note: It does not work. You cannot assign to a function call.) – MisterMiyagi Oct 29 '21 at 08:14
  • `self` is a `Robot` instance. `type(self)` is *`Robot` itself*. In Python, everything is an object, *including the classes themselves*. That means `Robot` is itself an object, and as such, it has attributes, and as such you can assign to such attributes. – Karl Knechtel Oct 29 '21 at 10:46

0 Answers0