+ 2
Get key, value inside class
What is the best way to get a key or a value of a dictionary inside a function of a class!? example: class Test: def test_func(self): my_dict = { 'a': 1, 'b': 2, } The best way to get the keys or values?
8 ответов
+ 4
Thank you Eduardo Petry for your point about making more than one object and its disadvantages!
+ 3
Dolan Hêriş There is a disadvantage of doing it that way. Each time you call Test() you are actually creating an object of the Test class and then the garbage collector immediately destroys it. So you are essentially creating 3 objects. The way I did, I created just one object that can be used indefinitely as long as the program runs. (Even though I used it only once)
+ 3
~ swim ~ no mind my friend, thanks for your help
+ 2
You need to return the dictonary to be able to manipulate it from outside the function/class.
class Test:
def test_func(self):
my_dict = {
'a': 1,
'b': 2,
}
return my_dict
test_object = Test()
dict_outside_class = test_object.test_func()
for key, value in dict_outside_class.items():
print(key, value)
+ 2
@~ swim ~ I think your way is not working for getting them inside a function of a class!
+ 2
Wow, have learnt from you guys. consider this: how would you work with list in dictionary. when two of the keys have list and these list. are integers.eg
Phy= []
students = {"name":"ken","test":[2,6,6,9],"practicals":[10,13 ,19,24,20],"exam":47"
"name":harry":"test":[6,9 7,7],"practicals":[19 25,22,27,27],"exam":38,
is it possible to print out the sum of the test value divide by 2 while that of the practical side by 3.
+ 1
Eduardo Petry or a clearer way to me:
class Test:
def test_func(self):
my_dict = {
'a': 1,
'b': 2,
}
return my_dict
for key, value in Test().test_func().items():
print(key, value)
for key in Test().test_func().keys():
print(key)
for value in Test().test_func().values():
print(value)