The following code only works if I comment out the initialiser.
class What:
def __init__(self):
pass
def method1(self):
print 'method1'
def main():
b = What()
if hasattr(b,"method1"):
print "b.method1"
b.method1()
main()
If it's not commented out I get the error message…
Traceback (most recent call last):
File "strange.py", line 17, in <module>
main()
File "strange.py", line 15, in main
b.method1()
AttributeError: What instance has no attribute 'method1'
However if I type in an identical method and call it, there is no problem at all…
def method2(self):
print 'method2'
I've od -c the file and there are no strange characters in the text
Using Python 2.7.2
I think you are mixing tabs and spaces.
With the code using 4 spaces per indent (spaces in accordance with pep8) it works fine. But this
class What:
def __init__(self):
pass
def method1(self):
print 'method1'
def main():
b = What()
if hasattr(b,"method1"):
print "b.method1"
b.method1()
main()
Is what Python would see if you had tabs for method1, and this will generate the error you see.
Related
When I compile I get this error:
Traceback (most recent call last):
File "c:/Users/dvdpd/Desktop/ProjectStage/Main.py", line 1, in <module>
class Main:
File "c:/Users/dvdpd/Desktop/ProjectStage/Main.py", line 6, in Main
test = Reading()
NameError: name 'Reading' is not defined
Code:
class Main:
print("Welcome.\n\n")
test = Reading()
print(test.openFile)
class Reading:
def __init__(self):
pass
def openFile(self):
f = open('c:/Users/dvdpd/Desktop/Example.txt')
print(f.readline())
f.close()
I can't use the class Reading and I don't know why.
Main and Reading are in the same file so I think I don't need an import.
Forward declaration doesn't work in Python. So you'll get an error only if you create an object of the Main class as follows:
class Main:
def __init__(self):
print("Welcome.\n\n")
test = Reading()
print(test.openFile)
# Main() # This will NOT work
class Reading:
def __init__(self):
pass
def openFile(self):
f = open('c:/Users/dvdpd/Desktop/Example.txt')
print(f.readline())
f.close()
# Main() # This WILL work
Python source files are interpreted top to bottom by the interpreter.
So, when you call Reading() inside class Main, it does not exist yet. You need to swap the declarations to put Reading before Main.
You need to define Reading before Main
You need to define class Reading before class Main.
class Reading:
def __init__(self):
pass
def openFile(self):
f = open('c:/Users/dvdpd/Desktop/Example.txt')
print(f.readline())
f.close()
class Main:
print("Welcome.\n\n")
test = Reading()
print(test.openFile())
How can I inherit a GTK+3 class in python ? I'm trying to create a inherited class of Gtk.Application and what I got is a segfault.
I've tried a lot of things, but with this I got a segfault:
class Program(Gtk.Application):
def __init__(self):
super().__init__(self)
...
prg = Program.new("app_id", flags)
if I try your code snippet I actually get:
Traceback (most recent call last):
File "pyclass.py", line 12, in <module>
prg = Program.new("app_id", 0)
TypeError: Application constructor cannot be used to create instances of a subclass Program
which is expected, since you're trying to call the Python wrapper for gtk_application_new() by using Program.new().
you should use the Python constructor form:
class Program(Gtk.Application):
def __init__(self):
Gtk.Application.__init__(self,
application_id="org.example.Foo",
flags=Gio.ApplicationFlags.FLAGS_NONE)
prg = Program()
sys.exit(prg.run(sys.argv));
this will actually warn you that you haven't implemented the GApplication::activate virtual function, which can be achieved by overriding the do_activate virtual method in your Program class:
class Program(Gtk.Application):
def __init__(self):
Gtk.Application.__init__(self,
application_id="org.example.Foo",
flags=Gio.ApplicationFlags.FLAGS_NONE)
def do_activate(self):
print("Activated!")
this will print Activated! on the console, before quitting.
I am trying to create a class with multiple functions, accepts a string as an argument and prints this string. So far this is what I have written:
class test():
def func(self,text):
print str(text)
test.func('This is a bunch of text')
To which I get the following error message:
_Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unbound method func() must be called with test instance as first argument (got str instance instead)_
Any suggestions?
You need to instantiate a class before you can call an instance method:
class Test(object):
def func(self, text):
print str(text)
test = Test()
test.func('This is a bunch of text')
Or you can try -
class test():
#staticmethod
def func(text):
print str(text)
test.func('This is a bunch of text')
I have two files, one of the test.py is
import new.py
class Test:
def __init__(self):
return
def run(self):
return 1
if __name__ == "__main__":
one=Test()
one.run()
and new.py
class New:
def __init__(self):
one.run()
New()
Now when i run python test.py I get this error,
Traceback (most recent call last):
File "test.py", line 1, in <module>
import new.py
File "/home/phanindra/Desktop/new.py", line 5, in <module>
New()
File "/home/phanindra/Desktop/new.py", line 3, in __init__
one.run()
NameError: global name 'one' is not defined
But I want to use this instance of one in my New!!
Can I do this??
edit:
I want to access the variable in test.py in new.py to do some process and give them back to test.py. Isn't this possible?
If you want your New class to use the instance of Test you created, you have to pass it in as part of the constructor.
new.py
class New:
def __init__(self, one):
one.run()
test.py
import new
class Test:
def __init__(self):
return
def run(self):
return 1
if __name__ == "__main__":
one=Test()
two = new.New(one);
Playing around with globals is a great way to break your code without realizing how you did it. It is better to explicitly pass in the reference you want to use.
No, you can't. The closest you can get is to pass the thing you need in to the constructor:
class New(object):
def __init__(self, one):
one.run()
one is defined inside the if __name__=='__main__' block.
Consequently, one will get defined only if test.py is run as a script (rather than imported).
For the module new to access one from the test module, you'll need to pull one out of the if __name__ block:
test.py:
class Test:
def __init__(self):
return
def run(self):
return 1
one=Test()
if __name__ == "__main__":
one.run()
Then access one by the qualified name test.one:
new.py:
import test
class New:
def __init__(self):
test.one.run()
New()
I'm trying to work out what's not working in this code:
#!/usr/bin/python
import cmd
class My_class (cmd.Cmd):
"""docstring for Twitter_handler"""
def __init__(self):
super(My_class, self).__init__()
if __name__ == '__main__':
my_handler = My_class()
Here's the error I get
Traceback (most recent call last):
File "main.py", line 12, in <module>
my_handler = My_class()
File "main.py", line 9, in __init__
super(My_class, self).__init__()
TypeError: super() argument 1 must be type, not classobj
If I change the superclass of "My_class" to an object it works fine. Where am I going wrong?
super() only works for new-style classes
cmd.Cmd is not a new style class in Python 2.5, 2.6, 2.7.
Note that your code does not raise an exception in Python 3.0.
So if super() doesn't work use :
import cmd
class My_class(cmd.Cmd):
def __init__(self):
cmd.Cmd.__init__(self)
You can still use super() if your MyClass extends object. This works even though the cmd.Cmd module is not a new-style class. Like this:
#!/usr/bin/python
import cmd
class My_class (cmd.Cmd, object):
"""docstring for Twitter_handler"""
def __init__(self):
super(My_class, self).__init__()
if __name__ == '__main__':
my_handler = My_class()