Python class error: "str object is not callable" - python-2.7

I was just practicing class and object
The code is
I already know the second function def name is overlapped since name is already set as self.name. but I am not sure how it makes error.
Can anyone tell how to fix this problem?

The error is pretty descriptive; strings aren't callable, functions are. I believe Python will look for variables within the class before it checks if there are functions with a given name. Thus, the string name is found but because it has () added to it, python then tries to call it like a function and fails.
Simply rename the function or the variable. You could use self._name as the variable name if you want to indicate that it's private and shouldn't be changed - at least not from outside the class. You'll also have to write print "The University name is %s" % (self._name) (and self.rank).

You already have a variable called name in your class University, so the program is trying to call "University of America"(), which triggers an error. Thus, change the function name to something like print_name:
class University():
def __init__(self, name, rank):
self.name = name
self.rank = rank
def print_name(self):
print "The University name is %s" % (self.name)
print "This University is ranked at %s" % (self.rank)
>>> users = University("University of America", "#1")
>>> users.name #The string of the name
'University of America'
>>> users.print_name()
The University name is University of America
This University is ranked at #1
>>>

Related

Different display for pringing same variable in python 2.7.11 class method

I am learning python just now, and confusing a lot question of python.
Below is one question:
class people:
def __init__(self,name):
self.name = name
print self.name
p = people('test')
test
p.name
'test'
why different output for people('test') and p.name? string test with/without single quote?
When you explicitly print something, you get the str() of that object. When you type an expression in the Python interpreter, you get the repr() of that object. Generally speaking, repr is more detailed, and gives some indication of the type of the object; often it is identical to a Python expression that would create that object. In particular, repr of a string is always enclosed in quotes, so that you can tell that it is a string.

Tkinter Input Substitutions

I've been working on a text based game in Tkinter, and I need a way so as to allow more flexibility with input. Basically, what I'm looking for is how to code:
if Input.get() == "look at" Item:
Item.look()
But with the flexibility of 'item' being a class, with subclasses, all of which can be 'looked at'. This is my current (non-working) code for this segment:
def Check():
if Output == "look at" Item:
Item.look()
else:
pass
class Item():
def __init__(self, name, description, value, quantity):
self.name = name
self.description = description
self.value = value
def look(self):
Look.Title = "{}".format(self.name)
Look.Description = "{}".format(self.Description)
Look.Value = "{} is worth {}.".format(self.name, self.value)
Details.insert(Look.Title)
Details.insert(Look.Description)
Details.insert(Look.Value)
Details.insert(Look.Quantity)
class Headphones(Item):
def __init__(self):
super.__init__(name = "Headphones", description = "A set of high quality white headphones.", value = 150)
Any help is much appreciated,
Blaze
You will need to do some sort of mapping between the input and the functions you want to call. You will need to parse the string in order to pull out the object from the input string and use the result of the parsing to look up the proper object or class.
For example, you could use a regular expression to parse the string "look at X", and then use "X" as an index into a dictionary in order to know what class to instantiate.
Here's a simple example:
import re
class Headphones(object):
def look(self):
print("you are looking at headphones")
class Goggles(object):
def look(self):
print("you are looking at goggles")
class Unknown(object):
def look(self):
print("I don't know what you're looking at")
def check(input):
map = {
"goggles": Goggles,
"headphones": Headphones,
}
match = re.match(r'look at (.*)', input)
if match:
thing = match.group(1)
cls = map.get(thing, Unknown)
object = cls()
object.look()
for phrase in ("look at headphones",
"look at goggles",
"look at something else"):
check(phrase)
Note: this is one of many ways to solve the problem. The point is, you need to:
write a parser that can pull out the important parts from the input, and
use the result of the parsing stage to decide how to process the data
The parser can be anything from simply splitting the input on spaces and grabbing the last word, to using a regular expression, to using a full blown parser using something like pyparsing.

Create instance of class from list (Python 2.7)

I'm trying to make a simple RPG game. I have a list of people that will be in the game, and want to create a character for each of them.
people = ['Mike','Tom']
class Character(object):
def __init__(self,name):
self.name = name
self.health = '100'
for x in people:
[x] = Character(x) # This is where I don't know what to do / if it's possible
That way I can call a character easily like
for x in people:
print ("%s: %s health" % (people[x].name, people[x].health))
Is such a thing possible, or am I going about this wrong? I read over How do I create a variable number of variables? but it seemed like dictionaries were the ultimate fix for their problem, and I have no idea how that would work in this situation.
It looks like you're just wanting to keep a list of Character objects. You don't need to reference people once you have that.
characters = [Character(person) for person in people]
Then, to print the character stats:
for c in characters:
print ("%s: %s health" % (c.name, c.health))

I am trying to explain my gf how functions work.. heres the code in python but i cant get a way out

askForAge()
takeDecision()
def askForAge():
age = int(input("Enter Age: "))
def takeDecision():
if age>=12:
allowPermission
return
else:
considerPermission()
return
def allowPermission():
print("You are allowed in the park. Enjoy!")
def considerPermission():
if age<9:
print("You are not allowed in the park.")
elif age>=9 and age<12:
print("You need supervision.")
How does this not work? I am trying to explain functions to my gf. I calling the functions and defined them aswell.
You are using age as a local variable, it doesn't keep it's value once each function returns.
You need to mark age global so that multiple functions can work on it. Do this by declaring it outside of the functions with a dummy value, and prefix each function's body with global age.
In addition, you need to add parentheses to your call of allowPermission.

Can you translate this debugging macro from C++ to python?

I use this very helpful macro when developing in C++:
#define DD(a) std::cout << #a " = [ " << a << " ]" << std::endl;std::cout.flush();
Could you help me implement the same idea in python? I don't know how the #a could be implemented with a python function...
As #Andrea Spadaccini and #adirau point out, it is not possible to reliably map values back to Python variable names. You could trawl through all namespaces looking for some variable name that references the given value, but that would be fighting the system and liable to return the wrong variable name.
Much easier it is to just pass the variable name:
import inspect
def pv(name):
frame,filename,line_number,function_name,lines,index=inspect.getouterframes(
inspect.currentframe())[1]
# print(frame,filename,line_number,function_name,lines,index)
val=eval(name,frame.f_globals,frame.f_locals)
print('{0}: {1}'.format(name, val))
a=5
pv('a')
yields:
a: 5
You could inspect the stack trace and "parse" it. Since you know the name of your function (dd in this case) it becomes fairly easy to find the call and extract the name of the variable.
import inspect
import re
def dd(value):
calling_frame_record = inspect.stack()[1]
frame = inspect.getframeinfo(calling_frame_record[0])
m = re.search( "dd\((.+)\)", frame.code_context[0])
if m:
print "{0} = {1}".format(m.group(1), value)
def test():
a = 4
dd(a)
test()
Output
a = 4
I think that this cannot be done.
The debugging macro that you posted works because it is expanded before compilation, during pre-processing, when you know the variable name. It is like you write all those couts by yourself.
Python does not have a pre-processor (AFAIK), there are external tools that do a similar thing (pyp and others), but you can not define a macro with the standard language.
So you should do your trick at run-time. Well, at run-time you don't know the "name" of the variable because the variable is just a reference to an object, when you call a method you call it on the object, not on the "variable". There can be many variables that point to that object, how does the object know which variable was used to call the method?
You can't get a variable (well, object)'s name in python. But you can pass the object's name to get its value (kinda the opposite of what you do with that macro)
>>> a=4
>>> locals()['a']
4
EDIT: a detailed explanation may be found here
import sys
def DD(expr):
frame = sys._getframe(1)
print '%s = %s' % (expr, repr(eval(expr, frame.f_globals, frame.f_locals)))
GLOBAL_VAR = 10
def test():
local_var = 20
DD('GLOBAL_VAR + local_var')
>>> test()
GLOBAL_VAR + local_var = 30
The Rod solution is perfectly usable.
It could be even extended to handle many vars.
But you can get close to that with much less magic:
def dd(**kwargs):
print ", ".join(str(k) + "=" + str(v) for k, v in kwargs.iteritems())
a = 1
dd(a=a,b=3)
output:
a=1, b=3