Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
152 views
in Technique[技术] by (71.8m points)

oop - Python method after create an object

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

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

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...