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.
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()
Solution 2:
SOLUTION IS:
class User:
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"