How to use getattr and string for calling class? - python

somelist=[1,2,3,4,5]
class HI:
a="QWERTY"
def test(wannacall):
test1="testing"+str(wannacall)
print(getattr(test1,"a")) #<- this part makes error 'str' object has no attribute 'a'.
testing1=HI()
test(somelist[0])
I know why this error happens, but I can't solve this.
(Sorry for my bad English.)
Edit: I know why that error happens, but I want to make code shorter than this:
somelist=[1,2,3,4,5]
class HI:
a="QWERTY"
def test(wannacall):
if wannacall==1:
print(getattr(testing1,"a"))
test1="testing"+str(wannacall)
testing1=HI()
test(somelist[0])
because the code will be longer if there are more classes. (ex: testing2, testing3, testing4).
+++ I solved this with eval() — my friend helped me.
print(getattr(eval(test1),"a"))

Your problem comes from not using getattr correctly.
The getattr() method takes multiple parameters:
1.object - object whose named attribute's value is to be returned
For example:
HI= HI() #declare the class
getattr(HI,.....)
2.name - a string that contains the attribute's name
For example:
getattr(HI, "a", ...)
3.default (Optional) - value that is returned when the named attribute is not found
For example:
getattr(HI, "a", "QRDefult")
What you are doing in your way is your using a string as the first parameter instead of an object. Just because your string has the same name as your object doesn't mean its an object.
you can do this instead
somelist=[1,2,3,4,5]
class HI:
b="QWERTY"
def test(object, wannacall):
test1="testing" + str(wannacall)
print(test1)
print(getattr(object,"b")) #<- this part makes error 'str' object has no attribute 'a'.
object=HI()
test(object,somelist[0])

Related

What is the difference between using magic method of a class with following syntaxes in Python: method(member) and member.__method__()?

I created a class and specified the attributes of the member with the following code:
Mexico_66 = Product('Mexico 66 VIN', 99.90, 4)
In the class, I have defined the following magic method:
def __len__(self):
print(self.quantity)
When I try to use this magic method with the following syntax: len(Mexico_66), the code executes but gives off an error at the very end: TypeError: 'NoneType' object cannot be interpreted as an integer
However, when executing the code with the following syntax: Mexico_66.len(), no error appears.
I don't quite understand why the error is caused in the first case and what is the difference between the 1st and 2nd options of executing magic method. I would be grateful if someone could explain it.
The __len__ magic method is supposed to return something, in this case, probably return self.quantity. You are getting the type error because your method implicitly returns None.
The idea of using these magic methods is to define behavior for commonly used functions like len(). If you call it using instance.__len__(), you are not utilizing the magic method, you are simply calling it like a regular instance method, which is why you don't see any error in that use case

Why does the python help class interpret sub-classes of the str class as module names?

When the python help function is invoked with an argument of string type, it is interpreted by pydoc.Helper.help as a request for information on the topic, symbol, keyword or module identified by the value of the string. For other arguments, help on the object itself is provided, unless the object is an instance of a subclass of str. In this latter case, the pydoc.resolve function looks for a module with a name matching the value of the object and raises an exception if none is found.
To illustrate this, consider the example code:
class Extra(object):
def NewMethod(): return 'New'
Cls1 = type( 'FirstClass', (str,Extra), {'__doc__':'My new class','extra':'An extra attribute'})
inst1 = Cls1('METHODS')
help( 'METHODS' )
help( inst1 )
The first invocation of help produces information on the topic "METHODS", the 2nd produces an error message because the pydoc.resolve function is trying to find a module called "METHODS".
This means that it is difficult to provide effective documentation for user defined sub-classes of str. Would it not be possible for pydoc.resolve to use a test on the type of the object, as is done in pydoc.Helper.help, and allow instances of user defined sub-classes to be treated as other class instances?
This question follows from earlier discussion of a related question here.
The simple answer is that making user-defined subclasses of str is not the most common case—partly because the user-defined data but not the string data would be mutable. By the time you have to deal with such, it’s imagined that you know how to write help(type(x)), and using isinstance rather than type(…) is … is the correct default in general. (The other way, you’d have to use help(str(x)) if you wanted to use it, like any other string, to select a help topic, but that’s surely even rarer.)

TypeError: sequence item 0: expected str instance, int found? [duplicate]

I have some code like:
def example(parameter):
global str
str = str(parameter)
print(str)
example(1)
example(2)
The first call to example works, but then the second time around I get an error like:
Traceback (most recent call last):
File "test.py", line 7, in <module>
example(2)
File "test.py", line 3, in example
str = str(parameter)
TypeError: 'str' object is not callable
Why does this happen, and how can I fix it?
If you are in an interactive session and encountered a problem like this, and you want to fix the problem without restarting the interpreter, see How to restore a builtin that I overwrote by accident?.
Where the code says:
global str
str = str(parameter)
You are redefining what str() means. str is the built-in Python name of the string type, and you don't want to change it.
Use a different name for the local variable, and remove the global statement.
Note that if you used code like this at the Python REPL, then the assignment to the global str will persist until you do something about it. You can restart the interpreter, or del str. The latter works because str is not actually a defined global variable by default - instead, it's normally found in a fallback (the builtins standard library module, which is specially imported at startup and given the global name __builtins__).
While not in your code, another hard-to-spot error is when the % character is missing in an attempt of string formatting:
"foo %s bar %s coffee"("blah","asdf")
but it should be:
"foo %s bar %s coffee"%("blah","asdf")
The missing % would result in the same TypeError: 'str' object is not callable.
In my case I had a class that had a method and a string property of the same name, I was trying to call the method but was getting the string property.
Note that TypeError: 'str' object is not callable means only that there is an attempt to call (i.e., use function-call syntax) a string (i.e., any name that previously had a string assigned to it). Using any other built-in method as variable name can cause the exact same error message.
You can get this error if you have variable str and trying to call str() function.
Whenever that happens, just issue the following ( it was also posted above)
>>> del str
That should fix it.
Another case of this: Messing with the __repr__ function of an object where a format() call fails non-transparently.
In our case, we used a #property decorator on the __repr__ and passed that object to a format(). The #property decorator causes the __repr__ object to be turned into a string, which then results in the str object is not callable error.
Check your input parameters, and make sure you don't have one named type. If so then you will have a clash and get this error.
str = 'Hello World String'
print(str(10)+' Good day!!')
Even I faced this issue with the above code as we are shadowing str() function.
Solution is:
string1 = 'Hello World String'
print(str(10)+' Good day!!')
I had the same error. In my case wasn't because of a variable named str. But because I named a function with a str parameter and the variable the same.
same_name = same_name(var_name: str)
I run it in a loop. The first time it run ok. The second time I got this error. Renaming the variable to a name different from the function name fixed this. So I think it's because Python once associate a function name in a scope, the second time tries to associate the left part (same_name =) as a call to the function and detects that the str parameter is not present, so it's missing, then it throws that error.
This error can also occur as a result of trying to call a property (as though it were a function):
class Example:
#property
def value():
return 'test'
e = Example()
print(e.value()) # should just be `e.value` to get the string
This problem can be caused by code like:
"Foo" ("Bar" if bar else "Baz")
You can concatenate string literals by putting them next to each other, like "Foo" "Bar". However, because of the open parenthesis, the code was interpreted as an attempt to call the string "Foo" as if it were a function.
it could be also you are trying to index in the wrong way:
a = 'apple'
a(3) ===> 'str' object is not callable
a[3] = l
it is recommended not to use str int list etc.. as variable names, even though python will allow it.
this is because it might create such accidents when trying to access reserved keywords that are named the same
This error could also occur with code like:
class Shape:
def __init__(self, colour):
self.colour = colour
def colour(self):
print("colour:", self.colour)
myShape = Shape("pink")
myShape.colour()
In the __init__ method, we assign an attribute colour, which has the same name as the method colour. When we later attempt to call the method, the instance's attribute is looked up instead. myShape.colour is the string "pink", which is not callable.
To fix this, change either the method name or the variable name.
I also got this error.
For me it was just a typo:
I wrote:
driver.find_element_by_id("swal2-content").text()
while it should have been:
driver.find_element_by_id("swal2-content").text
In my case, I had a Class with a method in it. The method did not have 'self' as the first parameter and the error was being thrown when I made a call to the method. Once I added 'self,' to the method's parameter list, it was fine.
FWIW I just hit this on a slightly different use case. I scoured and scoured my code looking for where I might've used a 'str' variable, but could not find it. I started to suspect that maybe one of the modules I imported was the culprit... but alas, it was a missing '%' character in a formatted print statement.
Here's an example:
x=5
y=6
print("x as a string is: %s. y as a string is: %s" (str(x) , str(y)) )
This will result in the output:
TypeError: 'str' object is not callable
The correction is:
x=5
y=6
print("x as a string is: %s. y as a string is: %s" % (str(x) , str(y)) )
Resulting in our expected output:
x as a string is: 5. y as a string is: 6
It also give same error if math library not imported,
import math
I realize this is not a runtime warning, but PyCharm gave me this similarly-worded IDE warning:
if hasattr(w, 'to_json'):
return w.to_json()
# warning, 'str' object is not callable
This was because the IDE assumed w.to_json was a string. The solution was to add a callable() check:
if hasattr(w, 'to_json') and callable(w.to_json):
return w.to_json()
Then the warning went away. This same check may also prevent the runtime exception in the original question.

'property' object is not callable

So I have am connecting to a contract, and that seems to work fine, I am trying to use this class: web3.personal.Personal from https://web3py.readthedocs.io/en/stable/web3.personal.html and I dont seem to understand what i am dong wrong... when i print(web3.personal.Personal) gives me back a class object but I cant seem to use any functions associated with this class, says I am missing "self" argument
contract_abi = my_abi
w3 = Web3(HTTPProvider(myurl))
myContract = w3.eth.contract(address ,abi)
ref = ref = web3.personal.Personal('web3')
print(ref) #this works
print(ref.newAccount(password='the-passphrase')) #This crashes
TypeError: newAccount() missing 1 required positional argument: 'self'
TypeError: 'property' object is not callable
It seems that web3.personal.Personal is a class, so in order to create a object you need to say ref = web3.personal.Personal()
Please note, classes are often (but not always) written with a capital letter.

how to assign variable to module name in python function

I have a set of modules, and I want to be able to call one of them within a function based on an argument given to that function. I tried this, but it doesn't work:
from my.set import modules
def get_modules(sub_mod):
variable = sub_mod
mod_object = modules.variable
function(mod_object)
I get:
AttributeError: 'module' object has no attribute 'variable'
It's not taking the argument I give it, which would be the name of a module that exists under my.set.modules. so if I called the function get_modules(name_of_mod_under_modules), I would like the line modules.variable to be "modules.name_of_mod_under_modules" which I could then have as an object passed to mod_object.
In your current code, you're looking for modules.variable which doesn't exist, hence the error! That's not how you get an attribute of an object.
To achieve what you wanted, use the getattr function.
mod_object = getattr(modules, variable)

Categories