Concatenating variable with "self" in PyQt5 [duplicate] - python

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.

Related

Need to append elements of the list into the function [duplicate]

This question already has answers here:
What is getattr() exactly and how do I use it?
(14 answers)
Closed 1 year ago.
for top in [eye_patch,hat]:
test1 = pa.test(top_type=pa.TopType.top)
This is the code I wrote but I need it to basically say
test1 = pa.test(top_type=pa.TopType.eye_patch)
after which it runs
test1 = pa.test(top_type=pa.TopType.hat)
how do I get it to do this?
If you want to call an object's attribute by it's name, you need to use the getattr('name') function and pass your function name as a string.
Your code would look like this:
for top in [eye_patch,hat]:
test1 = pa.test(top_type=getattr(pa.TopType, top.__name__)())
top.__name__ is for getting the function name as a string to call it as an attribute.
I think what you exactly want is:
from pa import test, TopType
for top in [TopType.eye_patch, TopType.hat]:
test1 = test(top_type=top)
or an alternative:
from pa import test, TopType
for top in ['eye_patch', 'hat']:
test1 = test(top_type=getattr(TopType, top))
but make sure that eye_patch and hat are both methods of the TopType.

How to create an instance of a class from a string name of the instance? [duplicate]

This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 2 years ago.
I would like to create several instances of a Class, I tried to make a for loop to name them differently.
Something like this, which doesn't work because the instance name is not supposed to be a string:
class A:
pass
for i in range(10):
"a"+str(i) = A()
Here the result I expect is 10 instances of the class A named: a0, a1, ... , a9.
How should I do?
You can use dictionaries,
classes = {}
for i in range(10):
classes[f"a{i}"] = A()
Then you can access the class instance like this classes["a7"].
i can think in two ways.
The trash way and a good way
Thrash:
class A:
pass
for i in range(10):
eval("a"+str(i)) = A()
Good:
class A:
pass
a= []
for i in range(10):
a[i] = A()

call method without parenthesis in python [duplicate]

This question already has answers here:
What's the pythonic way to use getters and setters?
(8 answers)
Closed last month.
what modification i would need to do in the below function computeDifference to get result printed in the console, instead of object message.
i know i need to add parenthesis () to call function to get the result printed in the console, but is there any other way to print the result?
class Difference1:
def __init__(self, a):
self.__elements = a
def computeDifference(self):
self.difference = max(self.__elements)- min(self.__elements)
return self.difference
a = [5,8,9,22,2]
c = Difference1(a)
print(c.computeDifference)
Make it a property
class Difference1:
#property
def computeDifference(self):
...
print(c.computeDifference)
However, I would change the name to difference. The idea of a property is that you shouldn't know or care whether the value is computed at that time or is stored as an attribute of the object. See uniform access principle.
You could add a magic function:
class Difference1:
...
def __str__(self):
return str(self.computeDifference())
...
>>> a = [5,8,9,22,2]
>>> c = Difference1(a)
>>> print(c)
20

Have a Function Take a Variable Name of an Object [duplicate]

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.

how do you reference a class instance with a variable in python? [duplicate]

This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 7 years ago.
I'm new to Python and I've searched for an answer but can't find one. Maybe I'm just asking it the wrong way...
As an example, if I have a class as follows:
class Person(object):
def __init__(self, name):
self.name = name
I create a couple instances as follows and can get their attributes like this:
person1 = Person("John")
person2 = Person("Mike")
print person1.name
print person2.name
What I want to do is substitute "personX" with a variable, and this is the part I haven't figured out yet. I'd like to to use this to iterate through a list of names that map to class instances and get/set their attributes.
name1 = "person1"
print "%s".name % (name1) <--- this fails with "AttributeError: 'str' object has no attribute 'name'
Whenever you want to create variableX where X is an incrementing number, you really want a list:
people = []
people.append(Person('John'))
people.append(Person('Mike'))
for person in people:
print person.name
print people[0].name
Use eval() to get instance referenced by the created string this way
name1 = "person1"
print eval(name1).name
Typically, this is considered bad practice, especially with the use of eval and exec to do so:
people = {'person1': Person('Bob'), 'person2': Person('Sam')}

Categories