This question already has answers here:
error in python d not defined. [duplicate]
(3 answers)
Closed 8 years ago.
Class Gui: # будущее гуи, получает данные о спортсмене
# и передает в класс Person
def input(self):
self.inputName =input("name")
return self.inputName
the_app=Gui()
print the_app.input()
How to decide my problem?
Please help
now, i get this error
Traceback (most recent call last):
File "/home/julia/COURSEWORK/person.py", line 34, in <module>
print the_app.input()
File "/home/julia/COURSEWORK/person.py", line 29, in input
self.inputName =input("name")
File "<string>", line 1, in <module> NameError: name 'j' is not defined
In Python 2.x, input evaluates its input as real Python code. In other words, it is equivalent to this:
eval(raw_input())
To fix the error you showed, you need to use raw_input instead, which does not evaluate its input but returns it as a string object.
Also, Python is case-sensitive. Moreover, all keywords, including class, are lowercase. So, when you run that code, you will get a NameError saying that Class is undefined (I don't know how you got to the point you did without encountering this. Perhaps you made a typo when posting here?)
Finally, in Python 2.x, all classes should inherit from the object built-in in order to make them "new style" classes. You can read about those here.
All in all, your code should look like this:
class Gui(object): # будущее гуи, получает данные о спортсмене
# и передает в класс Person
def input(self):
self.inputName = raw_input("name")
return self.inputName
the_app = Gui()
print the_app.input()
Related
I have developed a python framework that is being used by others. In order to print any data to the output, the developer should use a Log class (Log.print(...)) and should not use the print() method directly. Is there any ways to force this rule throughout the code? For example, by throwing an error when a developer uses the print method directly like this:
Error: print method cannot be called directly. Please use Log.print().
Suppressing print (as discussed here) is not a good idea as the developer might get confused.
Actullay, below two line code are the same:
sys.stdout.write('hello'+'\n')
print('hello')
so, you can redirect sys.stdout to a class which raise a exception at calling print.
import sys
class BlockPrint():
call_print_exception = Exception('Error: print method cannot be called directly. Please use Log.print().')
def write(self, str):
raise self.call_print_exception
bp = BlockPrint()
sys.stdout=bp
print('aaa')
Output:
Traceback (most recent call last):
File "p.py", line 12, in <module>
print('aaa')
File "p.py", line 7, in write
raise self.call_print_exception
Exception: Error: print method cannot be called directly. Please use Log.print().
I am currently working through Automate the Boring Stuff with Python and was given this example in Chapter 4 (You can read the page here if you're curious). The code was typed from the example given in the book as suggested and is pasted below. In the book, I am told the response I get is supposed to prompt me to enter a pet name, and if it doesn't match what's in the list I should get a response saying that I don't have a pet by that name.
The problem I run into is that the response I ACTUALLY get is :
Enter a pet name:
Gennie
Traceback (most recent call last):
File "/Users/gillian/Documents/Python/AutomateTheBoringStuffwithPython/Ch4Example1.py", line 3, in <module>
name = str(input())
File "<string>", line 1, in <module>
NameError: name 'Gennie' is not defined
I'm not sure why that would be. I don't see anything different about my code from the example, but something about that error seems not right. Can anyone tell me where I've gone off course?
myPets = ['Zophie', 'Pooka', 'Fat-tail']
print('Enter a pet name: ')
name = input()
if name not in myPets:
print('I do not have a pet named ' + name)
else:
print(name + ' is my pet.')
Change input() into raw_input() as you seem to be using python 2.x and this code is written in 3.x.
Find out more about differences here.
This question already has an answer here:
What does "del" do exactly?
(1 answer)
Closed 6 years ago.
Some source code is like below:
class Flask(object):
def __init__(self, value):
self.value = value
def _get(self):
return self.value
def _set(self,value):
self.value = value
name = property(_get, _set)
del _get, _set
app = Flask('abc')
app.name = 'hello'
My question is why this source code block can work. Class method _get, _set was deleted by del sentences. Why we also can use app.name to call the Flask._set method?
As the comment says, they're not really deleted as there are references to them (held by the property) but they (as names) are removed from the class itself, therefore writing
app = Flask('abc')
app._get()
app._set('foo')
is not possible because Flask class no longer has these members.
del deletes the name and the memory if nothing else references it.
Since you copied the reference when doing name = property(_get, _set), del has not the effect you're believing it has (imaging the disastrous effects of a forced deletion, for instance in a C++ code. That would make the python runtime unstable)
You cannot access _get and _set methods directly (by name), but they're still referenced somewhere.
Small, simpler example:
l=[3,4,5]
x=l
del l
print(x)
print(l)
result:
[3, 4, 5] # <== x is valid
Traceback (most recent call last):
File "L:\module1.py", line 5, in <module>
print(l)
NameError: name 'l' is not defined
you see that x has kept the data. But accessing l raises NameError
This question already has answers here:
What is the python "with" statement designed for?
(11 answers)
Closed 7 years ago.
Hey guys am trying to use the with statement in my code..Since am new to python i just wrote to code to understand the working of with statement..My code
class Employee:
empCount = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
c = Employee("blah",1)
c.empCount = ['aad']
class Subin(Employee):
def __init__(self, name, salary):
self.name = name
self.salary = salary
def __enter__(self):
return self
def __exit__(self ,type):
print 'ok'
def babe(self):
with c.empCount as b:
return 0
b = Subin("sds",1)
b.babe()
When I run the code I get the error:
Traceback (most recent call last):
File "C:/Python27/dfg", line 38, in <module>
b.babe()
File "C:/Python27/dfg", line 33, in babe
with c.empCount as b:
AttributeError: __exit__
Can you guys tell me why this is happening?
Firstly, Python code is not "free form". If your indentation is incorrect, it will not compile or run. Cutting and pasting your code into an interpreter will show you that.
Secondly, you're using the with statement wrongly. It's not the Subin class that should work as a context manager (with __enter__ and __exit__ methods although the latter has the wrong number of arguments) but the c.empCount object which is a list here and therefore won't work.
The with statement is described here in the official documentation some examples are provided.
I'd recommend that you play with basic python a little more before trying out context managers.
I am just starting out with object-oriented programming and I am trying to make a game about taking care of a character.
Here is part of my code:
class Game(object):
def __init__(self):
self.hunger = 30
self.thirst = 30
self.fun = 30
self.energy = 30
.........................
def new_character():
name = input("Name your character: ")
name = Game()
name()
But when I run this, I get:
Traceback (most recent call last):
File "C:\Python34\Virtual Human Simulator.py", line 185, in <module>
new_character_init()
File "C:\Python34\Virtual Human Simulator.py", line 182, in new_character_init
name()
TypeError: 'Game' object is not callable
I have been searching the internet for people who might have asked that question, but all I got was Type errors with modules and data types, not with classes, and the documentation doesn't help at all.
What is the cause of this problem and how to resolve it?
As the error points out, you're trying to use the newly created object as a function. name() . Unless your class has the __call__ method defined, this will fail. It would probably be more useful to tell us what you're trying to achieve