How to make dictionary element an object in python? - python

How to make dictionary element an object in Python?
I made a class…
class Qs:
def __init__(self,list1,id,quest="",mark=1):
self.__list1=list1
self.__id=id
self.__quest=quest
self.__mark=mark
self.__list1.update({self.__id:{self.__quest:self.__mark}})
How can I store objects in a dictionary so I can call functions in this class like this?
dictionary[1].print()

what you probably want is another class that includes a dictionary in it:
class QuestionCollection:
def __init__(self):
self.listofquestions = dict()
def print(self,question_number):
print(dictionary[question_number])
Then you could do this:
classobject = MyClass()
classobject.listofquestions[1] = Qs(...)
classobject.print(1)
or,
classobject = MyClass()
print(classobject.dictionary[1])
Then, you could extend this class to include other functions that operate on your entire dictionary.

Related

Making custom Attributes in Python

I'm new to python so I don't know much.
I was defining a function to work with lists and I want that function to be used like an attribute. For example to sort a list we use: list.sort()
Basically, instead of using the function like function(list) I want to use it like this: list.function()
You have to create a class
class MyClass():
def function(self, param):
print(param)
myClass = MYClass()
myClass.function()
You can see here or here for more details
You'll have to make a class that inherits the list class.
class MyList(list):
def __init__(self, *args):
super().__init__(*args)
def all_caps(self):
return [item.upper() if isinstance(item, str) else item for item in self]
mylist = MyList(['hi', 'hello', 1234])
mylist.all_caps()
You will have to create a custom class that inherit from original list and then using builtins module assign new extended class to previous list:
import builtins
class my_list(list):
def f(self):
return sum(self)
builtins.list = my_list
arr = list([1,2,3])
x = arr.f()
print(x)
Output:
6
Warning
Remember that you need to create every list using list() function to make sure your method will work.

Iterate over python class

I am learning how to do OOP with python. I would like to create a class B that contains an array/list of classA and execute a function in a for loop.
Here is an example:
class A:
def __init__(self, name):
self.name = name
def printSomething(self):
print (self.name)
class B:
def __init__(self, listOfNames):
# struture to store a list of objects A based on the list of names supplied
def printSomething2(self):
for i in # struture to store a list of objects A based on the list of names supplied :
i.printSomething()
names = ["a,b,c,d"]
obj = B(names)
obj.printSomething2()
what python structure is suitable for storing multiple objects? How can I set the size of it based on the input of the class?
For can I iterate over the created structure to call a function?
Best Regards
You could just use:
class B():
def __init__(self,listOfNames):
self.name_objs = []
for name in listOfNames:
self.name_objs.append(A(name))
def printSomething2(self):
for i in self.name_objs:
i.printSomething()
Still this is dynamic and getting the size to set this before is rather hard but this would work

Dynamically set dict elements with getattr

I already see the post Dynamically get dict elements via getattr?, but i can't solve my problem.
I want do something similar, but I'm a bit confused. I want set (not get) the data in the correspondent dictionary, but I get this error
AttributeError: type object 'Dictionary' has no attribute 'VERBS'.
My code is:
class Dictionary:
def __init__(self):
self.VERBS = dict()
self.REFERENCER = dict()
def setDictionary(self, fileDictionary, name):
methodCaller = Dictionary()
dictionary = "self."+name.upper()
dictionary = getattr(Dictionary, name.upper())
dictionary = fileDictionary.copy()
Can you see what I'm doing wrong? Because I don't understand completely that.
I think that this is what you are looking for:
class Dictionary:
def __init__(self):
self.VERBS = dict()
self.REFERENCER = dict()
def setDictionary(self, fileDictionary, name):
setattr(self, name.upper(), fileDictionary)
This uses setattr to assign fileDictionary to the member with the name name.upper() on self
The error that the code in the question has results from attempting to access the name on the class where it doesn't exist rather than on the instance where it exists.
It is also possible to write the method as:
def setDictionary(self, fileDictionary, name):
dictionary = getattr(self, name.upper())
dictionary.update(fileDictionary)
Which might be closer to what you were attempting.
Note that these two behave differently if the passed dictionary is mutated. The first binds the object to the name on the instance. The second updates the existing dictionary with the items from the passed dictionary.

Initialize an object built from a class with a specific dictionary

The goal is to build a class with an __init__ method that will allow to create objects which will be initialized with a specific dictionary.
Details:
A file mydicts.py is a collection of various dictionaries.
The object built from the class that I intent to create will be initialized to one of the dictionaries from mydicts.py.
mydicts.py example:
dict1 = {k1:v1, k2:v2,...,kn:vn}
dict2 = {k1:v1, k2:v2,...,km:vm}
etc.
My attempts:
class Example(dict):
def __init__(self, dictx):
self.dictx = getattr(__import__("mydicts", fromlist=['m']), dictx)
Results:
e = Example('dict1')
print e
{} # <- got empty dictionary. Want {k1:v1, k2:v2,...,kn:vn}
The goal is to create objects such that:
a = Example(dict1)
print a
# {k1:v1, k2:v2,...,kn:vn}
b = Example(dict2)
print b
# {k1:v1, k2:v2,...,km:vm}
Since you did not define a custom __str__ method for your class, print is calling the __str__ method of the parent class dict. Moreover, this is causing Python to print the empty dictionary created by the parent class in dict.__new__ instead of the dictionary that you have stored in self.dictx.
Because your class inherits from dict, you should be passing the dictionary returned by getattr to the __init__ method of the parent class. You can use super for this:
class Example(dict):
def __init__(self, dictx):
dct = getattr(__import__("__main__", fromlist=['m']), dictx)
super(Example, self).__init__(dct)
This will initialize the parent class with data taken from dct. In other words, the empty dictionary has been replaced with the dictionary returned by getattr. So, when print calls the parent's __str__ method, the correct output will be given:
>>> dict1 = {'k1':'v1', 'k2':'v2', 'kn':'vn'}
>>> class Example(dict):
... def __init__(self, dictx):
... dct = getattr(__import__("__main__", fromlist=['m']), dictx)
... super(Example, self).__init__(dct)
...
>>> e = Example('dict1')
>>> print e
{'k2': 'v2', 'k1': 'v1', 'kn': 'vn'}
>>>
An alternate solution would be to define a custom __str__ method for your class that returns self.dictx as a string:
class Example(dict):
def __init__(self, dictx):
self.dictx = getattr(__import__("mydicts", fromlist=['m']), dictx)
def __str__(self):
return str(self.dictx)
Note however that if you use this approach, there isn't really a reason to inherit from dict since your class is not a new type of dictionary; it just has a dictionary stored as an attribute.
I think you are making this far more complicated than it need be. Noting the manual says:
Direct use of __import__() is rare, except in cases where you want to import a module whose name is only known at runtime.
But you do know the module name at loading time, your data definition just has too many variable names. Much clearer would be my_dicts.py:
my_dicts = [
{k1:v1, k2:v2,...,kn:vn},
{k1:v1, k2:v2,...,km:vm},
…
]
and example.py:
import my_dicts
class Example(dict):
def __init__(self, n):
"""Returns an Example instance loaded with the nth element
of my_dict."""
super(Example, self).__init__(my_dicts.my_dicts[n])

returning a list from an objects elements?

I have a defined an object ( simplified below) and want to return an element as a list.
Is there an easier way than doing the below ?
class objectRecord(object):
def __init__(self,fields):
self.time=fields[0]
self.definition=fields[1]
self.name=fields[2]
self.source=fields[3]
self.size=fields[4]
self.value=fields[5]
self.increasedsize=fields[6]
self.count=fields[7]
rest of __init__ omitted
def getList(self):
return [self.name,self.definition,self.name,self.source,self.size,self.value,self.increasedsize,self.count]
rest of class omitted
You can get a dictionary containing all object attributes:
def get_attrs_dict(self):
return self.__dict__
If you just want the list of values:
def get_attrs_list(self):
return self.__dict__.values()
Here is one way to do it, via getattr():
def getList(self):
attributes = 'time definition name source'.split()
return [getattr(self, attribute) for attribute in attributes]
You can add more attributes to the list if needed.
As sort of a follow-up to Mark's comment: it looks an awful lot like what you actually want is to write your __init__ like this:
def __init__(self, fields):
self.fields = fields # or maybe fields[:] if you need to make a copy
self.definition, self.name, ... , self.count = self.fields
This is both a more convenient way to define your variables, and provides a very clear way to access all the values (through self.fields).

Categories

Resources