I have a list of class objects and each object has a variable val.
e.g.,
class my_class:
a = 3
lst = [my_class(), my_class()]
I would like to print all the object's val. How can this be done without iterating through the list?
I tried
print(lst.a)
print(lst[:].a)
Related
I created a class Demo in which I added a constructor with an empty dictionary in it. With the method addSomething inside the class I add key value pairs to this dictionary. The key which gets added is of type str and the value of type int. In another method useKeys in the same class I wanna access the key which I added to the dictionary. With the keys() method I only get the key like dict_keys([<__main__.Demo object at 0x7f7cd00c75b0>]). How can I make the str who was added visible?
Code
class Demo:
def __init__(self, someString):
self.something = dict()
def addSomething(self, something):
if something not in self.something:
self.something[something] = 0
self.something[something] += 1
def useKeys(self):
#prints dict_keys([<__main__.Demo object at 0x7f7cd00c75b0>])
print(self.something.keys())
something1 = Demo("ABC")
something2 = Demo("DEF")
something1.addSomething(something2)
print(something1.useKeys())
Edit
One suggestion in the comments is to use __str__. I understand that this method gets called always if an object from this class gets printed. But how can I make the key from the dictionary readable? My current implementation does not make the key readable:
def __str__(self):
return "{self.something}".format(self=self)
With the method addSomething inside the class I add key value pairs to this dictionary. The key which gets added is of type str and the value of type int.
No, it is not. The key which gets added is of type Demo and the value is of type int. This is why printing the dictionary keys is printing the __repr__ of a Demo object.
How can I make the str who was added visible?
You did not add any str. The strings passed as arguments in your code are never used.
You can either write the __repr__ function (which will override the object object function of the same name, from which every python3 class inherits), or you can use the argument someString you're already providing and that it's not being used at all, it's only forcing you to provide a string when creating a new instance of a Demo object:
Solution 1
Actually using the attribute someString from the constructor in the addSomething function.
With this solution, the key is indeed of the type str.
class Demo:
def __init__(self, someString):
self.something = dict()
self.someString = someString # Actually using the string provided at instance time
def addSomething(self, something):
## This method will use the attribute someString from object something instead
if something.someString not in self.something:
self.something[something.someString] = 0
self.something[something.someString] += 1
def useKeys(self):
## keys are now strings
print(self.something.keys())
something1 = Demo("ABC")
something2 = Demo("DEF")
something1.addSomething(something2)
print(something1.useKeys())
Solution 2
Overriding __repr__, but you require a string anyway so using someString from the constructor too.
With this solution, the key is of type Demo, but when you print that key, it'll display a string.
class Demo:
def __init__(self, someString):
self.something = dict()
self.someString = someString # Actually using the string provided at instance time
def addSomething(self, something):
## This method will use the something object as in the original code
if something not in self.something:
self.something[something] = 0
self.something[something] += 1
def __repr__(self):
## When something1.__repr__ is called, it'll display the someString provided at instance time
return self.someString
def useKeys(self):
## keys are objects, but will appear as strings because of the __repr__ method from that object
print(self.something.keys())
something1 = Demo("ABC")
something2 = Demo("DEF")
something1.addSomething(something2)
print(something1.useKeys())
The __str__ function of an object is used in another circumstance, it's not needed in your requirement.
You can just convert it into a list for easy representation:
print(list(something1.useKeys()))
By the way, it does seem like the class you're implementing already exists as collections.Counter.
I'm trying to call methods from a list that is filled with objects from a different class where the list is defined.
Consider the following:
class ObjectA(object):
def __init__(self, object_id):
self.id = object_id
def a_function(self):
return self.id
from ObjectA import ObjectA
class ObjectB:
def test():
object_1 = ObjectA(1) # passing the id
a_list = [ObjectA] # setting the list to be of type ObjectA (?)
a_list.append(object_1)
a_list[0].a_function() # Says I need to pass argument 'self'
How something like this would be possible? I know that I could instead do a_list[0].id and it works but it feels wrong. I prefer having setters/getters.
Edit: I'm also aware that if I declare the list like this a_list = [] instead of a_list = [ObjectA] it also works but in that case I don't have access to the methods for autocompletion.
In Python you can't specify the type of a list. So the line a_list = [ObjectA] makes no sense. (In fact it creates a list containing the class ObjectA, not an object, hence the self error.)
Replace a_list = [ObjectA] with a_list = [] to create an empty list
How to return a list of objects and not list here.
I want to return a list of test objects and not a list of str..
class test:
val = ""
def __init__(self,v):
self.val = v
def tolower(self,k):
k = k.val.lower()
return k
def test_run():
tests_lst = []
tests_lst.append(test("TEST-0"))
tests_lst.append(test("TEST-1"))
tests_lst.append(test("TEST-2"))
i_want_object_of_test = map(lambda x:x.val.lower(),tests_lst)
if __name__ == '__main__':
test_run()
OUTPUT:
['test-0', 'test-1', 'test-2']
i want a list of test objects where each object's val has changed to lower case.
The question is unclear. I'll answer by what I understand.
What I understand is that you are trying to create a new list of test objects, with the values as lower case.
You can do this either by changing the state of each of the objects in a for loop (changing state is usually not recommended):
for test_obj in test_lst:
test_obj.val = test_obj.val.lower()
A way to do it through a list comprehension is to create new test instances:
i_want_object_of_test = [test(test_obj.val.lower()) for test_obj in test_lst]
Besides, there are a few problems with your test class:
It is an old style class, you should always inherit from object in your classes: class test(object):
You define a class variable by putting val = ""' in your class defenition, you then override it in each instance.
Your tolower method gets another test instance (k) and returns its value as lower case. I assume you want to either return a new test object or change the current one in place. Either way the method should only use self.
I having difficulties to understand the instance of an object in a list.
How to save the value of an object into a list without saving the instance?
This is not possible isnt it?
The colde below works but i would like to avoid to use .value as i might have several parameters.. not sure if i am clear enough..
class BougieBuffer:
def __init__(self):
self.bougiebuffer=deque(maxlen = 10000)
self.maximum = Maximum()
def update(self,bougie):
self.maximum.value = random.randint(-1,1)
bougie.maximum.value = self.maximum.value
self.bougiebuffer.append(bougie)
print len(self.bougiebuffer)
for i in range (len(self.bougiebuffer),0,-1):
print self.bougiebuffer[i-1].prixFermeture, self.bougiebuffer[i-1].maximum.value
I would have wrote naturally something like below but obviously this is not working and it returns the same value for all
bougie.maximum = self.maximum
You want to create a copy of the Maximum() instance to assign to the bougie.maximum attribute; use either copy.copy or copy.deepcopy:
from copy import deepcopy
bougie.maximum = deepcopy(self.maximum)
You'll need deepcopy if there are any attributes of Maximum that are mutable; a list, dict, set or another custom class instance are all mutable, but things like integers and strings are not.
I am trying to write a wrapper object around the dictionary object in python like so
class ScoredList():
def __init__(self,dct={}):
self.dct = dct
list = ScoredList()
list.dct.update({1,2})
list2 = ScoredList()
list.dct.update({"hello","world"})
print list1.dct, list2.dct # they are the same but should not be!
It seems like I am unable to create a new ScoredList object, or rather, every scored list object shares the same underlying dictionary. Why is this?
class ScoredList2():
def __init__(self):
self.dct = {}
The above code for ScoredList2 works fine. But I want know how to overload the constructor properly in python.
A dictionary is a mutable object. In Python, default values are parsed when the function is created, meaning the same empty dictionary is assigned to every new object.
To solve this, simply do something like:
class ScoredList():
def __init__(self, dct=None):
self.dct = dct if dct is not None else {}