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()
Related
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 !
I have a class as below which within the __init__ method I am trying to assign a True/False value to a class property using a class method.
class Sensor:
def __init__(self, json_data):
self.sensor_eui = json_data['end_device_ids']['dev_eui']
self.reading1 = json_data['uplink_message']['decoded_payload']['temperature']
self.reading2 = json_data['uplink_message']['decoded_payload']['humidity']
self.tolerance_exceeded = self.tolerance_check
def tolerance_check(self):
sql = f"SELECT DefaultLowerLimit, DefaultUpperLimit FROM [dbo].[IoT_Sensors] WHERE
DeviceID = '{self.sensor_eui}'"
results = exec_sql(sql)
if (self.reading1 > int(results[0])) and (self.reading1 < int(results[1])):
return False
return True
The issue is, when trying to troubleshoot this and logging the objects to the console, instead of returning True or False as the assigned value of 'tolerance_exceeded' it returns the method and object:
logging.info(f'Tolerance Exceeded: {sensor.tolerance_exceeded}')
logs in the console as below:
[2022-10-26T12:08:08.025Z] Tolerance Exceeded: <bound method Sensor.tolerance_check of <__app__.IoT_Data-Handler.classes.Sensor object at 0x000001C834D45BE0>>
So what is going on here? I have not been coding long, but when I have done something similar in the past (assigning a string value from an API), it worked fine. This is for an Azure Function, but I cannot see how that would impact what I am trying to achieve.
Any help would be appreciated.
The issue in your code is that instead of calling the function you assign it. In order to call the function you have to add the parenthesis.
class Sensor:
def __init__(self, json_data):
self.sensor_eui = json_data['end_device_ids']['dev_eui']
self.reading1 = json_data['uplink_message']['decoded_payload']['temperature']
self.reading2 = json_data['uplink_message']['decoded_payload']['humidity']
# Calling tolerance_check and assigning return value to tolerance_exceeded
self.tolerance_exceeded = self.tolerance_check()
I have this class in a module1:
class A(models.Model):
_name="a"
b_id = field.Many2one("b")
tax_old = fields.Float()
tax_value = fields.Float(string="Tax", related = 'b_id.tax_value', store=True)
all_taxes = fields.Float(_compute='compute_all')
#api.depends('tax_value')
def compute_all(self):
self.all_taxes = self.tax_value + self.tax_old
self.update()
In module2 I have this class:
class B(models.Model):
_name="b"
a_ids = fields.One2many("a","b_id")
tax_value = fields.Float(string="Tax")
Now in A view when I change b_id value, tax_value works fine and compute_all works fine, but when I save this record, all_taxes doesn't take tax_value field, only tax_old. And when I open the record form view again and manually write a value in tax_value, it works totally fine.
It should be enough to use b_id on your compute method, because it's related:
#api.multi
#api.depends('b_id')
def compute_all(self):
for record in self:
record.all_taxes = record.b_id.tax_value + record.tax_old
The compute method can be called with a multi record recordset. So use a for loop inside it. And you don't have to do an update() at the end.
You can try it
#api.one
#api.depends('b_id', 'b_id.tax_value')
def compute_all(self):
self.all_taxes = self.tax_value + self.tax_old
Two things:
It ist compute not _compute and you don't need to use self.update().
Try this instead:
# You'll need this
from django.db.models import F
#api.depends('tax_value')
def compute_all(self):
self.update(all_taxes=F('tax_value') + F('tax_old'))
You're missing the self. What you've done is defined a local variable called all_taxes, not the instance variable.. which is what you're after
Here is Customer class:
class Customer:
def __init__(self, timestamp, cid, item_count):
self.time_stamp = timestamp
self.customer_name = cid
self.item_count = item_count
def checkout(self, new_timestamp):
self.time_stamp = new_timestamp
def get_cus_name(self):
return self.customer_name
If I create an empty list of Customer objects like:
customers = [Customer]
And then somewhere else I try to call Customer methods in a loop like:
def checkout_customer(self, cid):
for cus in self.customers:
if cus.get_cus_name == cid:
cus.checkout(self.cur_num_customers + 7)
why do I get an error when I try to call cus.checkout? My ide tells me that it expects a Customer but got an int. Why doesn't it pass itself into the 'self' arg here?
However if I just create a Customer object and directly call its methods, it works fine:
def foo(self):
cus = Customer(1,'pop',2)
cus.checkout(23)
This is my first time learning python, and ive been stuck trying to figure out lists, and accessing its members. Perhaps my initialization of self.custormers = [Customer] is incorrect?
EDIT:
In my constructor of tester class I create an empty list like this:
self.customer = [Customer]
I am able to add customers no problem:
def add_custormer(self, customer):
self.customers.append(customer)
My problem is not adding customers, but accessing their methods once they are in a list. Doing something like this self.customers[0].checkout(1,'pop',2) gives me an error "Expected type 'Customer' got int".
I am not sure of the class where checkout_customer lives but I am assuming you declare the list self.customers somewhere in it.
self.costumers = []
If you intend to add an element Customer to the list you should use something like: self.customers.append(Customer(x,y,z)) since you want to add a new customer to the list and when doing so you are required to initialize the Customer class.
I didn't try the code but I believe something like this should work:
def foo(self):
self.customers.append(Customer(1,'pop',2))
self.checkout_customers(23)
I'm trying to create a custom timestamp field.
class TimestampKey(models.CharField):
__metaclass__ = models.SubfieldBase
def __init__(self, *args, **kwargs):
import time
kwargs['unique'] = True
kwargs['max_length'] = 20
kwargs['auto_created'] = True
kwargs['editable']=False
super(TimestampKey, self).__init__(*args, **kwargs)
def to_python(self, value) :
return value
def get_db_prep_value(self, value) :
try:
import time
t = time.localtime()
value = reduce(lambda a,b:str(a)+str(b),t)
except ValueError:
value = {}
return value
class Table1(models.Model):
f = TimestampKey(primary_key=True)
n = ....
It stores the value with appropriate timestamp in the db. But it doesnt populate the field 'f' in the object.
Eg:
t1 = Table1(n="some value")
t1.f -> blank
t1.save()
t1.f -> blank.
This is the problem. Am I missing something so that it doesnt populate the filed?
Please shed some light on this.
Thanks.
Is it wise to use a timestamp as your primary key? If your database uses ISO 8601 or really any time format in which second is the smallest time interval... Well, anyway, my point is that you have no guarantee, especially if this is going to be a web-facing application that two entries are going to resolve within the minimum time interval. That is, if the smallest time interval is a second, as in ISO 8601, if you get two requests to save in the same second, you're going to get an error condition. Why not stick to automatically incrementing integer keys and just make the timestamp its own field?
The get_db_prep_value method only prepares a value for the database, but doesn't send the prepared value back to the Python object in any way. For that you would need the pre_save method, I think.
Fortunately, there's already an "auto_now" option on DateField and DateTimeField that does what you want, using pre_save. Try:
class Table1(models.Model):
f = models.DateTimeField(auto_now=True)
(If you must write your own pre_save, look at how auto_now modifies the actual model instance in /django/db/models/fields/__init__.py on lines 486-492:
def pre_save(self, model_instance, add):
if self.auto_now or (self.auto_now_add and add):
value = datetime.datetime.now()
setattr(model_instance, self.attname, value)
return value
else:
return super(DateField, self).pre_save(model_instance, add)
)