for example:
obj1 = ClassName()
obj1.name = "name1"
obj2 = ClassName()
obj2.name = "name2"
obj3 =开发者_JAVA技巧 ClassName()
obj3.name = "name3"
obj4 = ClassName()
obj4.name = "name4"
and we have static variable that return number of objects: ClassName.counter
How i can get obj1.name, obj2.name and other, but if objects count can be dynamic(using cycle for example) ?
PS: more good if you can say me how to do that in the python, but only design will be good also.
You can use a Factory
class, that's to say an object which handles creation and storing of ClassName
objects. Then you can easily access the different ClassName
s within an array in Factory
class (which must be a Singleton)
Well... it's actually not recommended to do this type of staff, being a little incomprehensible and prone to bugs...however, you could do it this way:
class MyClass(object):
names_list = []
_name = None
def get_name(self):
return self._name
def set_name(self, name):
assert self._name is None
self._name = name
self.names_list.append(name)
name = property(get_name, set_name)
obj1 = MyClass()
obj1.name = 'name1'
obj2 = MyClass()
obj2.name = 'name2'
print obj1.names_list
print len(obj1.names_list)
It works. It's ugly. Using some external factory to handle it is probably much better. If you want to store links to existing instances, some array/dictionary with weakrefs would probably be a fine solution.
精彩评论