Search code examples
pythonargumentsdefaultinitclass-variables

python refer to class variable while passing arguments to init


What I want to achieve:
1. Have a class variable keeping count of number of objects created
2. That variable should not be available to objects/others i.e. private to the class
3. If specific ID is not provided during init, use this counter variable to assign object.ID
I have following python code

class UserClass(object) :
    __user_id_counter = 0
    def __init__(self, UserID=__user_id_counter) :
        self.UserID = UserID
        __user_id_counter += 1

myuser = UserClass()

but I am getting UnboundLocalError: local variable '_UserClass__user_id_counter' referenced before assignment
I am new to python so kindly help me here :)


Solution

  • To access __user_id_counter an object or class reference is needed. In the argument list self or UserClass can not be accessed, hence:

    class UserClass(object) :
        __user_id_counter = 0
        def __init__(self, UserID=None) :
            self.UserID = self.__user_id_counter if UserID is None else UserID
            UserClass.__user_id_counter += 1