This question already has answers here:
How to access (get or set) object attribute given string corresponding to name of that attribute
(3 answers)
Closed 4 years ago.
If I have the following code:
class foo:
def __init__(self):
self.w = 5
self.z = 10
def sum(obj,x,y):
return obj.x+obj.y
f = foo()
print sum(foo,'x','y')
How would I create a function that takes in two unkown variable names and returns the sum of those variables variables?
In this case the example should print 15.
EDIT:
Typo for the last line it should say print sum(foo,'w','z')
All (I think?) python objects have a built-in __getattribute__ method. Use it like this:
def sum(obj,x,y):
return obj.__getattribute__(x)+obj.__getattribute__(y)
The method takes a string, and "unpacks" it to being a variable name.
Related
This question already has answers here:
How to access (get or set) object attribute given string corresponding to name of that attribute
(3 answers)
Closed 2 years ago.
I have 10 check-boxes and to check whether the checkbox is checked or not, I was trying to use loop. tacb1 is the name of the 1st checkbox, tacb2 is the name of 2nd checkbox and so on. I want to use a loop which looks something like:
for i in range(1,11):
if self.tacb'"+i+"'isChecked() == True:
print("hi")
else:
print("bye")
It is throwing the error for the line self.tacb'"+i+"'isChecked() as invalid syntax. How to concatenate a variable with self?
AlexLaur's answer using lists is the best way to do this but in the interest of completeness, here is an example of how you would use getattr to do the same thing
class MyClass:
def __init__(self):
self.item1 = 1
self.item2 = 2
self.item3 = 3
def check(self):
for i in range(1,4):
print(getattr(self,f'item{i}'))
c = MyClass()
c.check()
I think the best way to do this is to store all checkboxs instance into a list like that :
self.all_checkboxs = [checkox_a, checkox_b, ..., checkox_n]
And then you can iterate through like this:
for checkbox in self.all_checkboxs:
if checkbox.isChecked():
bar()
else:
foo()
If you really need to use strings, you can use python exec(), but I not recommend this way.
This question already has answers here:
What does ** (double star/asterisk) and * (star/asterisk) do for parameters?
(25 answers)
Closed 5 years ago.
I'm learning python, trying to figure out how does this code actually work:
def func(**args):
class BindArgs(object):
foo = args['foo']
print 'foo is ', foo
def __init__(self,args):
print "hello i am here"
return BindArgs(args) #return an instance of the class
f = func(foo=2)
Output:
foo is 2
hello i am here
But it's very confused that in the argument of a function func(foo=2) that takes equation mark in it. Could you please explain how the flow works?
Here is an abstract:
You call the function func and pass a dictionary as the argument to it.
In the func function, you define a class named BindArgs, and then in the return statement, you first make an object (instance) from the BindArgs class and then return that instance.
Notice that the statement foo = args['foo'] get the key value of 'foo' from the args dictionary (that is 2 in your sample code).
the init also will be run as the constructor of the class when you are creating an object.
This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 6 years ago.
I am trying to call an object from a variable. I know how to use getattr to call a function of an object using a variable but can't work out how to use a variable to define the object name. I have dragged some example code below:
class my_class(object):
def __init__(self, var):
self.var1 = var
var = "hello"
object_1 = my_class(var)
print object_1.var1 # outputs - hello
attribute = "var1"
# i can call the attribute from a variable
print getattr(object_1, attribute) # outputs - hello
object = "object_1"
# but i do not know how to use the variable "object" defined above to call the attribute
# now i have defined the variables object and attribute how can i use them to output "hello"?
Since object_1 and object are global variables, you may use the code below:
print(globals()[globals()['object']].var1) # "hello" is printed
or this:
print(getattr(globals()[globals()['object']], attribute)) # "hello" is printed
where
globals()['object'] represents "object_1" string
globals()[globals()['object']] represents object_1 object.
This question already has answers here:
python: class attributes and instance attributes
(6 answers)
Closed 8 years ago.
I have a simple question:
Say that I have the following class:
class step:
alpha = []
and my main has the following:
listofstep = []
for i in range(20):
z = step()
z.alpha.append(0)
listofstep.append[z]
why does len(listofstep[0].alpha) gives me 20?
As you define it, alpha is a class variable and not an instance variable. When you do z.alpha it always points at the same list, regardless of which instance it is. Try to define step like this:
class step:
def __init__(self):
self.alpha = []
This question already has answers here:
How to avoid having class data shared among instances?
(7 answers)
Closed 9 years ago.
I have the following code:
import math
class h:
vektor = [0,0]
rel_chyba = 0
def __init__(self, hodnota, chyba):
self.vektor[0] = hodnota
self.vektor[1] = chyba
self.rel_chyba = chyba*1.0/hodnota
def __rmul__(self, hod2):
return h(hod2.vektor[0]*self.vektor[0], math.sqrt(self.rel_chyba*self.rel_chyba+hod2.rel_chyba*hod2.rel_chyba))
v = h(12,1)
print v.vektor[1]
t = h(25,2)
print v.vektor[1]
My problem is, that v.vektor[1] prints 1 for the first time and 2 for the second time. All the attributes of the object v are assigned the values of the attributes from t.
How can I create two different objects?
Thanks for your answers
Don't declare vektor at class level, that makes it a class variable. Just declare it inside __init__:
def __init__(self, hodnota, chyba):
self.vektor = [hodnota, chyba]