Python - Parent method don't acess the value of variable children - python

Hi I'm having a problem in this classes I created the parent class extracao_nia with the method aplica_extracao for having the similar part of the execution that I use in others class and the diferent part is in the transform method definined in the children class
but I'm having an issue that the variables that I defined as list() are Null variable when I execute the code:
AttributeError: 'NoneType' object has no attribute 'append'
class extracao_nia:
def __init__(self, d=1, h=1, m=15):
self._data_base = "database"
self.UM_DIA = datetime.timedelta(days=d)
self.UMA_HORA = datetime.timedelta(hours=h)
self.INTERVALO = datetime.timedelta(minutes=m)
#property
def data_base(self):
return self._data_base
def aplica_extracao(self, SQL):
fim_intervalo = self.inicio + self.INTERVALO#
pbar = self.cria_prog_bar(SQL)#
while (fim_intervalo <= self.FIM):#
self.connector.execute(SQL,(self.inicio.strftime('%Y-%m-%d %H:%M'),fim_intervalo.strftime('%Y-%m-%d %H:%M')))#
for log in self.connector:#
self.transforma(log)
self.inicio = fim_intervalo
fim_intervalo = self.inicio + self.INTERVALO
class usuarios_unicos(extracao_nia):
def __init__(self, d=1, h=1, m=15, file='nodes.json'):
self._data_base = "database"
self.UM_DIA = datetime.timedelta(days=d)
self.UMA_HORA = datetime.timedelta(hours=h)
self.INTERVALO = datetime.timedelta(minutes=m)
self.file = file
self.ids = list()
self.nodes = list()
self.list_cpf = list()
def transforma(self, log):
context = json.loads(log[0])['context']
output = json.loads(log[0])['output']
try:
nr_cpf = context['dadosDinamicos']['nrCpf']
conversation_id = context['conversation_id']
nodes_visited = output['output_watson']['nodes_visited']
i = self.ids.index(conversation_id)
atual = len(self.nodes[i])
novo = len(nodes_visited)
if novo > atual:
nodes[i] = nodes_visited
except KeyError:
pass
except ValueError:
self.ids.append(conversation_id)
self.nodes = self.nodes.append(nodes_visited)
self.list_cpf = self.list_cpf.append(nr_cpf)

list.append returns None since it is an in-place operation, so
self.nodes = self.nodes.append(nodes_visited)
will result in self.nodes being assigned None. Instead you can just use
self.nodes += nodes_visited

Related

insg1 = Insegnante.from_string(iron_man, "Ingegneria") AttributeError: type object 'Insegnante' has no attribute 'from_string'

I have this code:
class Insegnante(Persona):
profilo = "Insegnante"
def __init__(self, nome, cognome, età, residenza, materie=None):
super().__init__(nome, cognome, età, residenza)
if materie is None:
self.materie = []
else:
self.materie = materie
def scheda_personale(self):
scheda = f"""
Profilo: {Insegnante.profilo}
Materie: {self.materie}"""
return super().scheda_personale() + scheda
def aggiungi_materia(self,nuova):
if nuova not in self.materie:
self.materie.append(nuova)
print("Elenco materie aggiornato")
When I try to use it like so:
insg1 = Insegnante.from_string(iron_man, "Ingegneria")
I get this error:
insg1 = Insegnante.from_string(iron_man, "Ingegneria")
AttributeError: type object 'Insegnante' has no attribute 'from_string'
What is wrong with the code? How can I fix it?
You are trying to call the from_string method of the Insegnante class, but this class has no method from_string.
you can implement it yourself:
class Insegnante(Persona):
profilo = "Insegnante"
def __init__(self, nome, cognome, età, residenza, materie=None):
super().__init__(nome, cognome, età, residenza)
if materie is None:
self.materie = []
else:
self.materie = materie
def scheda_personale(self):
scheda = f"""
Profilo: {Insegnante.profilo}
Materie: {self.materie}"""
return super().scheda_personale() + scheda
def aggiungi_materia(self,nuova):
if nuova not in self.materie:
self.materie.append(nuova)
print("Elenco materie aggiornato")
def from_string(param1, param2):
# build your Insegante object and return it
return ...

Python - working with dictionaries - error

Link: https://www.w3schools.com/python/trypython.asp?filename=demo_ref_dictionary_update
def read_wpl_file(self,start,filename):
self.tree = ET.parse(filename)
self.smil = self.tree.getroot()
self.head = self.smil.find("head")
self.title = self.head.find("title").text
self.body = self.smil.find("body")
self.seq = self.body.find("seq")
self.media = self.seq.findall("media")
self.songs = []
for song_in_playlist in self.media:
self.song = {}
self.song.update({"path": song_in_playlist.attrib("src")})
self.song.update({"album_title" : song_in_playlist.attrib("albumTitle")})
self.song.update({"album_artist" : song_in_playlist.attrib("albumArtist")})
self.song.update({"title" : song_in_playlist.attrib("trackTitle")})
self.song.update({"artist" : song_in_playlist.attrib("trackArtist")})
self.song.update({"duration" : song_in_playlist.attrib("duration")})
self.songs.append(self.song)
print(self.songs)
self.song.update({"path": song_in_playlist.attrib("src")})
TypeError: 'dict' object is not callable
The error "object is not callable" means that the object in question does not support the function call syntax (e.g. attrib("src")).
xml.etree.ElementTree.Element.attrib is a dict, so you have to use the bracket syntax (attrib["src"]) or other dict methods to access its elements.
def read_wpl_file(self,start,filename):
self.tree = ET.parse(filename)
self.smil = self.tree.getroot()
self.head = self.smil.find("head")
self.title = self.head.find("title").text
self.body = self.smil.find("body")
self.seq = self.body.find("seq")
self.media = self.seq.findall("media")
self.songs = []
for song_in_playlist in self.media:
self.song = {}
self.song.update({"path": song_in_playlist.attrib["src"]})
self.song.update({"album_title" : song_in_playlist.attrib["albumTitle"]})
self.song.update({"album_artist" : song_in_playlist.attrib["albumArtist"]})
self.song.update({"title" : song_in_playlist.attrib["trackTitle"]})
self.song.update({"artist" : song_in_playlist.attrib["trackArtist"]})
self.song.update({"duration" : song_in_playlist.attrib["duration"]})
self.songs.append(self.song)
print(self.songs)

How to get the local_rank attribute

the Engine code is as follows:
class Engine(object):
def __init__(self, cfg, custom_parser=None):
self.version = 0.01
self.state = State()
self.devices = None
self.distributed = False
self.logger = None
self.cfg = cfg
if custom_parser is None:
self.parser = argparse.ArgumentParser()
else:
assert isinstance(custom_parser, argparse.ArgumentParser)
self.parser = custom_parser
self.inject_default_parser()
self.args = self.parser.parse_args()
self.continue_state_object = self.args.continue_fpath
if 'WORLD_SIZE' in os.environ:
self.distributed = int(os.environ['WORLD_SIZE']) > 1
if self.distributed:
self.local_rank = self.args.local_rank
self.world_size = int(os.environ['WORLD_SIZE'])
self.world_rank = int(os.environ['RANK'])
torch.cuda.set_device(self.local_rank)
dist.init_process_group(backend="nccl", init_method='env://')
dist.barrier()
self.devices = [i for i in range(self.world_size)]
else:
# todo check non-distributed training
self.world_rank = 1
self.devices = parse_torch_devices(self.args.devices)
def setup_log(self, name='train', log_dir=None, file_name=None):
if not self.logger:
self.logger = get_logger(
name, log_dir, self.args.local_rank, filename=file_name)
else:
self.logger.warning('already exists logger')
return self.logger
I want to get local_rank,but when I just use Engine.local_rank ,it returns AttributeError: type object 'Engine' has no attribute 'local_rank'
like this
Your local_rank depends on self.distributed==True or self.distributed!=0 which means 'WORLD_SIZE' needs to be in os.environ so just add the environment variable WORLD_SIZE (which should be an integer)

How to parallelize a class method or share class object between processes in python?

I have created a class containing all its instances and need to parallelize the process of instantiation, but cannot solve the problem of sharing the class as a class object. Is it possible in python 2.7 using multiprocessing?
OUTPUT_HEADINGS = []
class MyContainer(object):
"""
"""
instances = []
children = []
#classmethod
def export_to_csv(cls):
with open(args.output, "w") as output_file:
f_csv = csv.DictWriter(output_file, fieldnames=OUTPUT_HEADINGS)
f_csv.writeheader()
for instance in cls.instances:
f_csv.writerow(instance.to_dict())
def __new__(cls, dat_file):
try:
tree = ElementTree.parse(dat_file)
cls.children = tree.findall("parent_element/child_element")
except ElementTree.ParseError as err:
logging.exception(err)
if not cls.children:
msg = ("{}: No \"parent_element/child_element\""
" element found".format(os.path.basename(dat_file)))
logging.warning(msg)
cls.children = []
return False
else:
instance = super(MyContainer, cls).__new__(cls, dat_file)
instance.__init__(dat_file)
cls.instances.append(instance)
cls.children = []
return True
def __init__(self, dat_file):
self._name = os.path.basename(dat_file)
self.attr_value_sum = defaultdict(list)
var1 = MyContainer.children[0].find("var1")
var2 = MyContainer.children[0].get("var2")
cat_name = "{}.{}".format(var1, var2)
if cat_name not in OUTPUT_HEADINGS:
OUTPUT_HEADINGS.append(cat_name)
# processing and summarizing of xml data
def to_dict(self):
return output_dict
def main():
i = 0
try:
for f in FILE_LIST:
i += 1
print "{}/{}: {} in progress...".format(i, len(FILE_LIST), f)
print "{}".format("...DONE" if MyContainer(f) else "...SKIPPED")
except Exception as err:
logging.exception(err)
finally:
MyContainer.export_to_csv()
if __name__ == '__main__':
FILE_LIST = []
for d in args.dirs:
FILE_LIST.extend(get_name_defined_files(dir_path=d,
pattern=args.filename,
recursive=args.recursive))
main()
I tried to use multiprocessing.managers.BaseManager, to create a proxy for MyContainer class, but it can only create an instance object this way. I want actually to parallelize the MyContainer(dat_file) call.

Unable to use values from a class into another class

I am trying to grab the values from a class and use that particular value into another class. However I keep getting this error - AttributeError: 'CustomNodeTranslator' object has no attribute 'start'
Basically I am trying to get/transfer the values of self.start and self.end to be used into the ChanFileExporter class
I am not exactly sure why it is not working but when I applied this similar method in another portion of the code, it is working fine.
Any advises are greatly appreciated!
class CustomNodeTranslator(OpenMayaMPx.MPxFileTranslator):
def __init__(self):
OpenMayaMPx.MPxFileTranslator.__init__(self)
def haveWriteMethod(self):
return True
def haveReadMethod(self):
return True
def filter(self):
return "*.chan"
def defaultExtension(self):
return "chan"
def writer( self, fileObject, optionString, accessMode ):
self.start = []
self.end = []
for opt in filter(None, optionString.split(';')):
optSplit = opt.split('=')
if optSplit[1] == '0':
startAnimation = cmds.findKeyframe(which='first')
endAnimation = cmds.findKeyframe(which='last')
self.start = startAnimation
self.end = endAnimation
class ChanFileExporter():
def __init__(self, transform, startAnimation, endAnimation, cameraObj):
self.fileExport = []
testClass = CustomNodeTranslator()
mayaGlobal = OpenMaya.MGlobal()
mayaGlobal.viewFrame(OpenMaya.MTime(1))
startAnimation = testClass.start
endAnimation = testClass.end
for i in range(int(startAnimation), int(endAnimation + 1)):
...
...
The first time you see start or end in CustomNodeTranslator is in the writer() method.
self.start = []
self.end = []
It is bad practice to add attributes outside of __init__(); and the reason why it fails for you is because you are referring to attributes that do not yet exist since they are created only after you call writer().

Categories