Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Problem: I need a special Method in Python that is executed AFTER the Object is created.

Suppose i have a situation:

    ##-User Class;
    class User:
        __objList = []        ## User Class register of userObjs;
        __init__(self, name):
            self.name = name

    ##-and i create new UserObj;
    user = User("John Doe")

How can i add this UserObj in User.__objList[] after creation of Object user? Is there a method in Python that executes after the object is initialized? PS.I need add this usrObj in User.__objList after userObj was created by class automatically.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
151 views
Welcome To Ask or Share your Answers For Others

1 Answer

Just add your code to the __init__ function, when you create an object the code in the __init__ function will run.

class User(object):
    __objList = []
    def __init__(self, name):
        self.name = name
        # append object to list after create object
        self.__objList.append(self)

    @classmethod
    def showObjList(cls):
        for obj in cls.__objList:
            print("obj: (%s), name: (%s)" % (obj, obj.name))

a = User("Joy")
b = User("Hank")

User.showObjList()

picture show result


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...