how to add Eobject - python

I'd like to create a function to add EObject. Previously I've created a function to check it.
import sys
def get_by_query_nam(e_obj, query_name, cls = None):
e_object_class = getattr(sys.modules["__main__"], "EObject")
return JavaList(getSBQuery(e_obj.get_java_object(), query_name), e_object_class)
this works as expected (using getName() to have the value name)
Now with the value from function "get_by_query_name" I want to add another value to it.
Thanks !

Related

Declaring class methods in a function and accessing its values from another function

I've never really used classes before, I just simply went the easy way (global variables), and now I would like to make my code right to avoid future complications.
This is my code:
from dearpygui.core import *
class Engine:
def __init__(self,serial,type,profile):
self.serial = serial
self.type = type
self.profile = profile
def apply_selected_file():
res = []
html_name= "example.html"
path= "C:/"
#Function that reads data from a file and saves selected data in a list
res = html_imp(path + '/' + html_name)
#I would like to remove the code below and use a class for each file instead
setvalue(sn1,es[0]) #shows a label with this value
setvalue(type1,res[1]) #shows a label with this value
setvalue(profile1,res[2]) #shows a label with this value
return res
def button():
#This was my initial idea but it doesn't seem to work.
# res = apply_selected_file()
# E = Engine(res[0],res[1],res[2])
I have in mind reading multiple HTML files so using a class would be much easier than declaring variables for each file:
1- Use apply_selected_file to read a file and assign values (s/n,type,profile) to a new class (E1,E2,E3,...,E20,...)
2- Use another function button() to access those stored class values.

return value using into another function

I am using return value of function into another function, I want to do first I check if function return value ? if yes then only use return value
I am able to do this but in my case function call two times reason also i know but how can I achieve it with function call for only one time
Actually I am new in programming please can anyone help me
Thank you in advance
from loginAuth import *
class DisplayInfo:
def displayInfo(self):
# create object of loginAuth class
obj = LoginAuth()
if obj.check_password_and_userid():
userid, userrole = obj.check_password_and_userid()
print(userid,userrole)
obj = DisplayInfo()
obj.displayInfo()
here method: check_password_and_userid() is a function of class LoginAuth
which return userid and userrole
output : 01 Admin
obj.check_password and userid() returns a tuple like (userid, user role) if it's true then you can just set data to a variable then play with the data.
from loginAuth import *
class DisplayInfo:
def displayInfo(self):
# create object of loginAuth class
obj = LoginAuth()
data = obj.check_password_and_userid()
if data:
userid, userrole = data
print(userid,userrole)
obj = DisplayInfo()
obj.displayInfo()

Set a nested object property from a dot notation string in python

I’m writing a function that takes in a parent object data and a string inputString that may or may not include dot notation to represent nested objects (i.e. ‘nestedObject.itemA). The function should set the inputString attribute of data to a random string. If the string inputString is a nested object, the function should set the nested object’s value to be a random string. I can’t figure out how to handle this all in a for-loop. I want to do something like this:
split_objects = value.split(“.”)
for item in split_objects:
data.__setattr__(item, get_random_string())
However, in the case of nested objects, the above would set the nested object to be a random string, instead of the field inside. Would someone be able to help me with the syntax to handle both cases? Thanks in advance…
You need to get a reference to data.nestedObject before you can use setattr to change data.nestedObject.itemA.
prefix, suffix = value.rsplit(".",1)
# now prefix is nestedOjbect and suffix is itemA
ref = getattr(data,prefix)
setattr(ref,suffix,get_random_string())
You need to get the reference as many times as there are dots in inputString. So, if you have an arbitrarily deeply nested structure in data
value = "nestedObject.nestedObject2.nestedObject3.itemA"
path, attribute = value.rsplit(".",1)
path = path.split(".")
ref = data
while path:
element, path = path[0], path[1:]
ref = getattr(ref, element)
setattr(ref, attribute, get_random_string())
Here is some example code I to demo a "setField" function I wrote that similar to what you are looking for:
def setField(obj, fieldPath, value):
fields = fieldPath.split(".")
cur = obj
# use all but the last field to traverse the objects
for field in fields[:-1]:
cur = getattr(cur, field)
# use the last field as the property within the object to be overwritten (not traversed)
setattr(cur, fields[-1], value)
# USE CASE EXAMPLE:
class PrintBase:
def dump(self, level=0):
for key, value in vars(self).iteritems():
print " "*(level*4) + key + ":", value
if isinstance(value, PrintBase):
value.dump(level+1)
class BottomObject(PrintBase):
def __init__(self):
self.fieldZ = 'bottomX'
class MiddleObject(PrintBase):
def __init__(self):
self.fieldX = 'middleQ'
self.fieldY = BottomObject()
class TopObject(PrintBase):
def __init__(self):
self.fieldA = 'topA'
self.fieldB = MiddleObject()
top_obj = TopObject()
print "=== BEFORE ==="
top_obj.dump()
print "=== AFTER ==="
setField(top_obj, 'fieldB.fieldY.fieldZ', '!!!! test value !!!!')
top_obj.dump()
And here is the example output:
=== BEFORE ===
fieldB: <__main__.MiddleObject instance at 0x7f5eb1cc6b48>
fieldX: middleQ
fieldY: <__main__.BottomObject instance at 0x7f5eb1cc6b90>
fieldZ: bottomX
fieldA: topA
=== AFTER ===
fieldB: <__main__.MiddleObject instance at 0x7f5eb1cc6b48>
fieldX: middleQ
fieldY: <__main__.BottomObject instance at 0x7f5eb1cc6b90>
fieldZ: !!!! test value !!!!
fieldA: topA

Python Class Method Line Not Running

An experienced VBA programmer here, that is starting the delve into Python OOP. I fear it is so simple, that I am having issues finding an answer without asking for help.
I have written the following code:
#Import packages
import openpyxl as xl
import os
class DataExtract:
#Initialize the class
def __init__(self,wb):
self.wb = wb
#Set class method to return sheet for named range
#classmethod
def rng_sht(cls,dest):
for title, coord in dest:
return(title)
#Set class method to return cell for named range
#classmethod
def rng_coord(cls,dest):
for title, coord in dest:
return(coord)
#Set class method to retun value of named range
#classmethod
def rng_val(cls,rng):
#Define destinations
dest = wb.get_named_range(rng).destinations
#Retrieve sheet
sht = DataExtract.rng_sht(dest)
coord = DataExtract.rng_coord(dest)
#Return value
return()
#Define workbook
wb = 'Test_WB'
#Initiate class
wb_cur = DataExtract(wb)
#Find temp for current sheet
Temp = wb_cur.rng_val('Temp')
I'm aware that my indentation is incorrect.
The issue that I am having is that when I call the rng_val class method, it is only returning the current value for the first method I call within (in this case, the "sht"). When I inactivate the "sht" line, the "coord" line functions correctly.
I suspect the issue is likely due to how I am calling class methods or how I have structured the class, but I am not sure.
Update
I have updated the code with feedback from all of you, with my script below. I am still having errors with exiting the loop in the rng_val class, which Max suggested yield to resolve. I attempted to fix to no avail.
#Import packages
import openpyxl as xl
import os
class DataExtract:
#Initialize the class
def __init__(self,wb):
self.wb = wb
#Set class method to return sheet for named range
#classmethod
def rng_sht(cls,dest):
for title, coord in dest:
return title
#Set class method to return cell for named range
#classmethod
def rng_coord(cls,dest):
for title, coord in dest:
return coord
#Set class method to retun value of named range
#classmethod
def rng_val(cls,wb,rng):
#Define destinations
dest = wb.get_named_range(rng).destinations
#Retrieve sheet
sht = cls.rng_sht(dest)
coord = cls.rng_coord(dest)
print(sht)
print(coord)
#Return value
return 1
path = 'C:\\Users\\User\\Desktop\\Python\\PracFiles\\'
#Loop through workbooks in a given folder
for i in os.listdir(path):
#Define workbook
wb = xl.load_workbook(path + i,data_only=True)
#Find temp for current sheet
Temp = DataExtract.rng_val(wb,'Temp')
There are several issues I can see that may have to do with your inexperience with Python OO.
The empty return statements cannot have parenthesis after them. That would cause the function to return an empty tuple instead of nothing.
If you plan on having your function return a value, place the value (or variable) immediately after the return statement like this: return coord. return on its own will just exit the function.
The first parameter in any class method contains the instance of that class when called via an object. You called it self in the constructor and cls in the other methods. They are the same thing. You haven't been using it in your code in places it looks like it should be. See below:
sht = DataExtract.rng_sht(dest)
coord = DataExtract.rng_coord(dest)
That would call the function rng_sht statically passing dest as an instance of DataExtract which I'm near certain isn't intended. What you should do instead is use cls.rng_sht(dest) to references the object instance. Also, you cannot access class fields by just referencing them by themselves, like wb.get_named_range(rng) where wb is a field in DataExtract. Instead reference it via cls like cls.wb.get_named_range(rng)

why do some functions within a python class require the use of brackets and others dont

Below I have defined a basic class with some functions.
I am not sure of the best way to pass data from one function to be used in another.
My solution was to pass a dataframe as a parameter to the function. I am sure there is a better and more technically correct way so please call it out.
What I am trying to understand is why some functions in the class require the () to be used when calling them and others you can call just using the function name.
Once a ASX object called "market" is initiated The two examples are:
market.all_companies()
Returns: a dataframe
market.valid_industry
returns a series
class YourError( Exception ): pass
class asx(object):
def __init__(self, name):
try:
#initialise
self.name = name
#all companies on asx downloaded from asx website csv
df = pd.read_csv('http://asx.com.au/asx/research/ASXListedCompanies.csv', skiprows=1)
df.columns = ["company","asx_code","industry"]
df["yahoo_code"] = df["asx_code"]+".AX"
self.companies = df
self.industry = self.all_industry(df)
self.valid_stocks = self.valid_stocks(df)
self.valid_industry = self.valid_industry(df)
except:
raise YourError("asx companies CSV not available")
def all_companies(self):
return self.companies
def valid_industry(self,df):
return df["industry"].value_counts()
def all_industry(self,df):
return df["industry"].value_counts()
def valid_stocks(self,df):
return df[(df["industry"]!= "Not Applic") & (df["industry"]!="Class Pend")]
market = asx("asx")
market.all_companies()
market.valid_industry
All functions require () but you're doing some nasty stuff in you __init__ where you replace function with a series.
self.valid_industry = self.valid_industry(df)
this will overwrite the function valid_industry to no longer be a function on the instance created but to be value returned from self.valid_industry(df)
don't use same name for member properties and methods and all will make sense.
For your methods you don't need to pass in df as argument as you have it assigned to self.companies so your
def valid_industry(self,df):
return df["industry"].value_counts()
becomes:
def valid_industry(self):
return self.companies["industry"].value_counts()

Categories