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)
Related
This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 2 years ago.
On my recent project I am facing with new obstruction where I need to declare a variable based on value of another string.
What I need:
'Hai'= 2
The String Hai is initialized at variable x,
x='hai' then I need 'hai'= 2
Now all I want is the value of x to point to a int (different int for different values of x).
So if,
x='bye'
then,
'bye'=20
You need to get a dictionary as #Saadat said:
x = {'hai': 2, 'bye': 20}
Now
x['hai']
Will give 2 and the other key will give 20
Or:
y='hai'
z = x[y] #z=2
Also another worse approach:
if x == 'hai':
hai = 2
elif x == 'bye'
bye = 20
...
As mentioned in the comments, you are describing a dictionary:
A dictionary provides a mapping between two different values (also known as an associative array in other languages). You can declare one in Python like this:
mydict = {"hai": 2, "bye": 20}
print(mydict["hai"])
# 2
print(mydict["bye"])
# 20
You can then use variables as the key to access the dictionary:
mykey = "bye"
print(mydict[mykey])
# 20
For more details, please see the Python docs for dictionaries
If you don't go with dictionary and need to declare a variable name & value at runtime. We can achieve this with setattr()
Try this,
class Sample:
pass
obj = Sample()
x = 'hai'
setattr(obj, x, 20)
print(obj.hai)
This question already has answers here:
Calling variable defined inside one function from another function
(6 answers)
Closed 2 years ago.
I have open source web server written in Python. Inside the server I have a wrong_checker() function which takes a value and checks it against real_value. I can access this function.
def wrong_checker(value_of_check):
return (value_of_check == "" or (not value_of_check and real_value)) \
or value_of_check != real_value
Now I want to write function find_value() to find and print the value of real_value.
def find_value():
???????
Well, normally you should write a comparer funciton
def compare(value_a, value_b):
#compare stuff and return 1, 0 or -1
#1 for value_a greater, 0 for equal and -1 for value_b greater
Then you are more flexible.
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:
Should I, and how to, add methods to int in python?
(1 answer)
Can I add custom methods/attributes to built-in Python types?
(8 answers)
Closed 5 years ago.
If I have a class such as this
class foo():
def __init__(self, value = 0):
self.__value = value
def __set__(self, instance, value):
self.__value = value
def calc(self):
return self.__value * 3
def __repr__(self):
return str(self.__value)
I can now make a variable of the class foo and use it's functions.
n = foo(3)
print(n.calc())
No problems there but if I keep going with something like this.
n = 5
print(n.calc())
I will get an error, because I have now set n to an int object with the value 5 and thus does not have the calc() function.
I normally work with C++ so I'm confused because I thought that the __set__ function was supposed to override the = operator and then set __value to the value of 5 just like if I were to to use
operator=(int value)
In C++, I have looked for an explanation but have not found any.
All help appreciated.
As stated here.
The following methods only apply when an instance of the class
containing the method (a so-called descriptor class) appears in an
owner class (the descriptor must be in either the owner’s class
dictionary or in the class dictionary for one of its parents).
This question already has answers here:
What is the purpose and use of **kwargs? [duplicate]
(13 answers)
Closed 7 years ago.
I'm testing to use kwargs and have a trouble.
This is the python3 code :
class B:
def __init__(self, **kwargs):
print(kwargs['city'])
a = {'phone':'0101', 'city':'Daejeon'}
b = B(a)
But, there is an error like below :
b = B(a)
TypeError: __init__() takes 1 positional argument but 2 were given
Is there something wrong in my code?
I think that I just exactly follow the tutorial....
Keyword arguments are not passed that way.
obj1 = B(phone='0101', city='Daejeon')
obj2 = B(**a)