Can you make a function that would create several instances of a class for you in Python?
Tag : python , By : Lex Viatkine
Date : March 29 2020, 07:55 AM
I hope this helps . You're very close! The usual approach is to use a dictionary, and to use the names you want as dictionary keys. For example: >>> class Room(object):
... def __init__(self, x, y):
... self.x = x
... self.y = y
...
>>> rooms = {}
>>> names = ['a', 'b', 'c', 'd']
>>> locations = [[1,1], [1,2], [2,1], [2,2]]
>>> for name, loc in zip(names, locations):
... rooms[name] = Room(*loc)
...
>>> rooms
{'a': <__main__.Room object at 0x8a0030c>, 'c': <__main__.Room object at 0x89b01cc>, 'b': <__main__.Room object at 0x89b074c>, 'd': <__main__.Room object at 0x89b02ec>}
>>> rooms['c']
<__main__.Room object at 0x89b01cc>
>>> rooms['c'].x
2
>>> rooms['c'].y
1
>>> for roomname, room in rooms.items():
... print roomname, room.x, room.y
...
a 1 1
c 2 1
b 1 2
d 2 2
|
Python class instances stored in a list to store seperate instances
Date : March 29 2020, 07:55 AM
will help you It looks like you want a class variable. The code should look like this: from datetime import datetime
class Sms_store:
store = []
message_count = 0
def __init__(self):
pass
def add_new_arrival(self,number,time,text):
Sms_store.store.append(("From: "+number, "Recieved: "+time,"Msg: "+text))
Sms_store.message_count += 1
newsms1 = Sms_store()
time = datetime.now().strftime('%H:%M:%S')
newsms1.add_new_arrival("23456",time, "hello, how are you?")
newsms2 = Sms_store()
time = datetime.now().strftime('%H:%M:%S')
newsms2.add_new_arrival("23456",time, "hello, how are you?")
print Sms_store.store
|
Automating creation of class instances in python for an undetermined amount of instances
Date : March 29 2020, 07:55 AM
it should still fix some issue Whenever you see the pattern: unit1, unit2, ... , unitN, you should probably be using a list to store them. If you want to create a new unit, just append a new unit to the list. Try this example: units = []
# Your Unit constructor handles the creation of a new unit:
# No need to create a special function for that.
units.append(Unit(1,1))
units.append(Unit(1,2))
# etc...
print(units)
|
How to best save a number of class instances in Python? Updated: how to pickle class instances that contains osgeo.ogr o
Date : March 29 2020, 07:55 AM
it helps some times Under the hood shelve uses pickle, so if your objects can not be pickled, shelve can't work with them. There might be a way to store the information from each object so that it can later be used to reconstruct that object through object instantiation, but we'd need to know the details of the object, and how to create one.
|
Best way to make decorator for unique class instances Python
Date : March 29 2020, 07:55 AM
wish help you to fix your issue You can use functools.lru_cache to store all instances in a cache, and set no limit on the cache size. When you call the constructor, you'll get a new instance, and it will be stored in the cache. Then whenever you call the constructor with the same arguments again, you'll get the cached instance. This also means that every object always has a reference from the cache. from functools import lru_cache
@lru_cache(maxsize=None)
class Test:
def __init__(self, val):
self.val = val
>>> a = Test(1)
>>> a2 = Test(1)
>>> a is a2
True
>>> b = Test(2)
>>> b2 = Test(2)
>>> b is b2
True
>>> a is b
False
class Test:
@lru_cache(maxsize=None)
def __new__(cls, *args, **kwargs):
return object.__new__(cls)
def __init__(self, val):
self.val = val
>>> Test(1) is Test(1)
True
>>> Test(1) is Test(2)
False
>>> class SubTest(Test): pass
...
>>> Test(1) is SubTest(1)
False
>>> SubTest(1) is SubTest(1)
True
|