Skip to content Skip to sidebar Skip to footer

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 = []

Solution 1:

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

classUser(object):
    __objList = []
    def__init__(self, name):
        self.name = name
        # append object to list after create object
        self.__objList.append(self)

    @classmethoddefshowObjList(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

Solution 2:

SOLUTION IS:

classUser:
        objList = []
        def__init__(self, name):
            self.name = name
            User.objList.append(self)

    #
    u1 = User("Mike")
    u2 = User("Jhon")

    #print(User.objList)

    ##>OUTPUT:## [<__main__.User object at 0x0170F8F0>,##  <__main__.User object at 0x01B25E50>]

THANKS to all :)

Post a Comment for "Python Method After Create An Object"