This question already has answers here:
Using a dictionary to select function to execute
(11 answers)
Closed 6 months ago.
How can I call a (string) method assigned to a dict value like this
dict = { True: ''.lower }
I tried
flip = True
print("A".dict[flip])
but then I get:
AttributeError: 'str' object has no attribute 'dict'
d = {True: lambda x: x.lower()}
flip = True
print(d[flip]('A'))
prints
a
Related
This question already has answers here:
How to get the original variable name of variable passed to a function [duplicate]
(13 answers)
Closed 1 year ago.
How to pass a variable for an f-string '=' debugging operator?
from datetime import datetime
def print_var(var):
print(str(datetime.now())[:19], end=' ')
print(f'{var = }')
test = 5
print_var(test)
I expect print_var(test) to print the variable name from outside the function, ie.
test = 5
Please refer to Python: Print a variable's name and value? for the context of the question.
In f-strings you need to put the variable that needs to be printed between accolades. Like this:
from datetime import datetime
def print_var(var):
print(str(datetime.now())[:19], end=' ')
print(f'var = {var}')
Running the test yields the following:
test = 5
print_var(test)
>>>2021-10-06 11:32:05 var = 5
This question already has answers here:
Why does adding a trailing comma after an expression create a tuple?
(6 answers)
Closed 2 years ago.
Please look at the below code.
signal = {
"id": "p752",
}
class Trigger:
def __init__(self, signal):
self.id = signal['id'],
print(type(signal['id']))
print(type(self.id))
def get_trigger(self):
print(self.id)
t1 = Trigger(signal)
t1.get_trigger()
The output I get is
<class 'str'>
<class 'tuple'>
('p752',)
I honestly don't know what is happening here. When I assign signal['id'] to 'id' inside the constructor why is changing to a tuple?
self.id = signal['id']
Trailing comma is to be removed so it is treated as a tuple
This question already has answers here:
Python equivalent to JavaScript function object
(3 answers)
Closed 4 years ago.
I am working in one Python program where I want to create one object like we do in JavaScript.
var obj = {"sum":function(a,b){return a+b;}}`
Can I do a similar thing in Python?
There are (at least) two ways of doing this:
test_obj = {
'a': 'a',
'func': lambda: print('test')
}
test_obj['func']()
Or:
def test():
print('test')
test_obj = {
'a': 'a',
'func': test
}
test_obj['func']()
This question already has answers here:
How to access a field of a namedtuple using a variable for the field name?
(5 answers)
Python: access class property from string [duplicate]
(4 answers)
Closed 4 years ago.
How can I use colname_1 to get a value for an attribute foo of a namedtuple?
from collections import namedtuple
colname_1 = 'foo'
colname_2 = 'bar'
Farm = namedtuple('Farm', 'foo bar')
farm = Farm('apple', 'banana')
farm.foo # OK
farm.colname_1 # of course this doesn't work!
Use getattr():
getattr(farm, colname_1) # 'apple'
From the named tuple docs:
To retrieve a field whose name is stored in a string, use the getattr() function
Alternately, although clunky, you can index into the ._fields attribute:
farm[[i for i, f in enumerate(farm._fields) if f == colname_1][0]] # 'apple'
This question already has answers here:
How can I represent an 'Enum' in Python?
(43 answers)
Closed 8 years ago.
I have declared the enum as follows in python.I don't know how to use them.When I create an instance of this class it gives error as two arguments are required one given.
class CBarReference(Enum):
ThisBar = 0,
NextBar = 1,
Undefined=2
a=CBarReference()
I know what error is but I don't know what to give as the second argument other than self.
You should never have to create an instance of an enum; they're all accessed directly from the class, and you can just assign them to variables as you like:
a = CBarReference.ThisBar
b = CBarReference.NextBar
c = CBarReference.Undefined
d = CBarReference.ThisBar
assert(a == d)
assert(b != a)
assert(b != c)