0

I've read throughly many posts here on the difference between class methods and instance methods. I understand them conceptually, but now I'm trying to figure out the more subtle nuances. In the example below, if I call User.createUser('xyz'), where does userId get stored? does it go to (*) below, i.e. on the instance? Or would it be as if I inserted userId = None where I have the comment # placeholder and the userId passed in from User.createUser('xyz') then assigns the class variable userId with 'xyz'?

class User():

    # placeholder


    def __init__(self, userId):
        self.userId = userId # (*)

    @classmethod
    def createUser(cls, userId):
        if not isValid(userId): # isValid may or may not be part of the class
            return False
        else:
            return cls(userId)

    # ... other methods
3
  • cls(userId) instantiates your class, and userId gets passed to __init__. So for User, the userId will be stored in the new instance. Commented Oct 12, 2018 at 14:30
  • cls(userId) works exactly the same as if you did User(userId), and where that value gets stored from there works exactly the same too… Commented Oct 12, 2018 at 14:30
  • in python 3 class is defined as such class User: without parenthesis unless if you want this class to inherent from another class then you use parenthesis class User(User2): Commented Oct 12, 2018 at 14:34

3 Answers 3

1

Your classmethod createUser returns a new instance of the User object. The parameter passed to it is stored as an attribute on this new User instance.

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

4 Comments

then why not return User(userId)?
In the case of your example, returning cls(userId) and User(userId) is identical. The difference only becomes apparent in a child class of User.
and what would that difference be?
The difference is that cls refers to the current class, where User refers to the User class in particular. If you have a child class SpecialUser(User), using cls in the createUser method means SpecialUser.createUser will return a SpecialUser instead of a User
0

The userId parameter is stored in the __init__ method.

The call to cls(userId) is equivalent to a call to User(userId)

Comments

0

In your case, neither. The return cls(userId) returns a new object*, and the userId is assigned to the self of the new object. So, it's neither a class nor an instance variable, it's an instance variable of another object.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.