Whenever I try this:
x = input(foo)
showstat(x)
def showstat(y):
print(y.thing)
It comes back as an error
'str' object has no attribute 'thing'
but I don't know how to change it's data type in order to make it function properly.
I just need to figure out how to make it read as:
print(foo.thing)
rather than the error:
print("foo".thing)
It sounds like you are trying to evaluate the input as a python expression so you can retrieve the variable with the name entered. Is this correct?
If so you can use
eval(x)
though safer would be something like
locals()[x]
I would personally do this to your input, not as part of the function, but it depends on exactly what else you're trying to do.
Related
I am currently trying to create a program that learns through user input, however it converts to a string automatically.
Here's the code. I use the shelve module to store the commands for the code.
ok = {str(name):func}
asd.update(ok)
print(asd)
data["cmd"] = asd
data.close()
The 'asd' list contains every command which has been extracted from the shelf. I want to update it and store it, so next time it updates when calling a command.
'func' is the variable that stores the name of the function am trying to call, but string objects cannot be called.
How do I solve this?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
EDIT:
This has been solved (I totally forgot about eval() )
Not sure what you're trying to achieve here, but from what I've understood you should have a look to eval()
The eval() function evaluates the specified expression, if the expression is a legal Python statement, it will be executed.
More information here
I have a python program with lots of text I want to align and .format seemed messy, so I planned on using .center(shutil.get_terminal_size().columns) on the end of a print like so:
import shutil
print("Hello world!".center(shutil.get_terminal_size().columns))
and should be returned centered in my console, and it is.
However, If I want to simplify this into a single function:
def align_center():
center(shutil.get_terminal_size().columns)
and add that to the end of a print fuction:
print("Hello World!".align_center())
(I've also tried it without the parentheses at the end of .align_center)
it returns:
AttributeError: 'str' object has no attribute 'align_center'
I'm pretty sure I had it working correctly earlier but I changed something and it stopped, Am I crazy and this simplification via a function isn't possible? Am I applying it wrong?
I don't think you ever had it working if you simply appended it to the string. That would make it an atrribute and the str object is unlikely to have an attribute that matches the name of an arbitrary method you created.
This might help: pass the string to the method and return it formatted. Something like this:
def align_center(s):
return s.center(shutil.get_terminal_size().columns)
then:
print(align_center(s))
Please forgive my noob status, but I have come across a construct I don't really understand and hope someone can explain it for me.
class Base(object):
def mogrify(self, column):
return self.mogrifiers.get(column.lower().strip()) or (lambda x: x)
...
class MyClass(some.package.Base):
def mogrifiers(self):
return {
'column1': (lambda x: datetime.datetime.fromtimestamp(int(x)))
}
...
class MyOtherClass(object):
def convert_columns:
...
new_row[colkey] = self.myclass.mogrify(colkey)(value)
This all works, but I'm trying to write a unit test and mock out MyClass.
As far as I can tell, mogrifiers returns a dictionary of all the columns and any transformations that are required.
The code I am testing calls mogrify (inherited from the Base class) with a specific column name in a string.
This tries to extract the column from the dictionary and returns the lambda function ? or if it doesn't exist in the dictionary, it returns a lambda that just gives the string back ?
So that just leaves me with the (value) bit in the code I'm trying to test. It's no clear what it does.
If I don't want to test the underlying conversion/transformation my mock could just return the simple lambda.
So I've done that, but it throws an exception on the call to mogrify saying:
E TypeError: 'str' object is not callable
Can anyone provide some clues what I'm missing here?
As far as I can tell, mogrifiers returns a dictionary of all the
columns and any transformations that are required.
That is correct, though as you've shown it it will create a fresh dictionary each time which seems unnecessary.
The code I am testing calls mogrify (inherited from the Base class)
with a specific column name in a string.
This tries to extract the column from the dictionary and returns the
lambda function ? or if it doesn't exist in the dictionary, it returns
a lambada that just gives the string back ?
Yes, that is also correct (except that a lambada is a dance, but I think you meant lambda again).
So that just leaves me with the (value) bit in the code I'm trying to
test. It's no clear what it does.
The call self.myclass.mogrify(colkey) returns a callable, the (value) simply calls it. It may be clearer if I rewrite like this:
fn = self.myclass.mogrify(colkey)
new_row[colkey] = fn(value)
splitting it into two lines will also make it clearer whether the problem is with the call self.myclass.mogrify(colkey) or fn(value). If as seems likely it is the fn(value) call it means your mocked mogrify is returning a str instead of returning a callable; it could however be that you got the mock wrong and the mocked mogrify method is actually a string.
I would suggest you rewrite as shown and also insert a print between the two lines and see what is actually being returned.
I'm starting to learn Python and I find it really interesting. I am trying to create my own module and I ran into a bump. The code goes like this:
def break_words(sentence):
words = sentence.split(' ')
return words
def sort_words (words):
sort_word=sorted(words)
return sort_word
The second function has argument words fed in by the first, and I think it should work since it has been returned, but on running filename.sort_words(words) in Python, it gives an error message of NameError:global name 'words' is not defined. And it's requiring me to define words like words=filename.break_words(sentence) before it runs the second function.
What's wrong with my code?
You should try to explain yourself better in future, it's very confusing to read and probably the reason nobody replied.
This is what I think you want to know:
import filename
words = filename.break_words('some sentence goes here')
print filename.sort_words(words)
Have you tried that?
edit:
Variables in Python are always defined in scopes, so defining one variable in a function means that it is not defined anywhere outside the function.
'return' simply returns the value of that variable to the caller.
Ive been trying search how to pass object reference in python and type cast it similar to Java but no to avail. I duno if this topic exists somewhere here.
My trouble is i have to pass the object reference to a class constructor. But i duno how to typecast the reference to an object. In java though I have accomplish this but i have to transfer the code to the server side.
many thanks,
Jack
class SearchRectangle:
def __init__(self, lower_left_subgrid_x, lower_left_subgrid_y, rectangle_width, rectangle_height):
self.min_subgrid_x = int(lower_left_subgrid_x)
self.max_subgrid_x = int(self.min_subgrid_x + rectangle_width -1)
self.min_subgrid_y = int(lower_left_subgrid_y)
self.max_subgrid_y = int(self.min_subgrid_y + rectangle_height -1)
...blah
class SearchRectangleMultiGrid:
# parent rectangle should be a SearchRectangle instance
def __init__(self, parent_rectangle):
self.parent_rectangle = SearchRectangle()parent_rectangle
# test codes
test_rect = SearchRectangle(test_subgrid.subgrid_x, test_subgrid.subgrid_y, 18, 18)
print "\n\nTest SearchRectangle";
print test_rect.to_string()
print test_rect.sql_clause
test_rec_multi = SearchRectangleMultiGrid(test_rect)
print "\n\nTest SearchRectangleMulti"
test_rec_multi.parent_rectangle.to_string()
Python is a dynamically typed language and as such, it doesn't make much sense to cast something unless you specifically need it in that type.
In Python you should use Duck Typing instead: http://en.wikipedia.org/wiki/Duck_typing
So instead of trying to convert parent_rectangle to a SearchRectangle() you should simply test if SearchRectangle() has the properties you need.
Or if you really want to be sure that you'll always get a SearchRectangle(), use isinstance like this:
if isinstance(parent_rectangle, SearchRectangle):
This might be a good read for you: http://dirtsimple.org/2004/12/python-is-not-java.html
There's no reason to cast anything in python. What are you trying to do? Just use the object like you would, and if it's not of the correct type it will fail. There's no such thing as casting since variable names don't have a type associated with them.
Further explanation:
Casting is the act of taking a pointer/reference to one type of object, and say to the compiler "Yeah, I know this is a foo reference but please pretend it is a bar reference".
Python do not have pointers/references in that sense (although in another sense, everything is references). Also, the compiler/interpreter doesn't care what the type is in the first place. Hence, casting is both impossible and pointless.
So in your example: Just skip the type casting. It'll work anyway. And if it doesn't. then make a question on that problem.