This question already has answers here:
class method with no arguments produces TypeError
(3 answers)
Closed 6 years ago.
class Person:
def __init__(self, name):
self.name = name
def printName():
print "my name is %s" % self.name
Mitchell = Person("Mitchell")
Mitchell.printName()
This code throws this error:
Traceback (most recent call last):
File "/home/mitch/Desktop/test.py", line 8, in <module>
Mitchell.printName()
TypeError: printName() takes no arguments (1 given)
I'm sure I did this correctly...
you missed the self param in the printName function definition
class Person:
def __init__(self, name):
self.name = name
def printName(self):
print "my name is %s" % self.name
Because you forgot to add self explicitly to printName instance method. It should have been like
def printName(self):
...
Python implicitly passes object instance to every instance method. Although not directly related to the question, try to use pep8 conventions when you are working with Python. According to pep8 function names are snake-cased not camel-cased and so are variable names. So use print_name and `mitchell' instaed of their camel and pascel-cased counterparts.
Related
This question already has an answer here:
How to access outer attribute class within inner class?
(1 answer)
Closed 3 years ago.
As a title, I have a versatility function in parent class that will share use in child class A.k.A inner class. In below, I need to pass outer_send function from parent class. then, use it with call inner_send function inside Identify class alias child class. The result will output Test.
class Device:
def __init__(self):
self.identify = self.Identify(self.outer_send())
def outer_send(message):
print(message)
def last_error(self):
return self.identify.error_info
class Identify:
def __init__(self, send):
self.inner_send() = send()
def set_error(self, error):
self.error_info = error
device = Device()
device.identify.inner_send('test')
I don't like the pattern and I would recommend designing it differently. However, this does what I think you want to do:
class Device:
def __init__(self):
self.identify = self.Identify(self._send)
def _send(self, message):
print(message)
class Identify:
def __init__(self, _send):
self.send = _send
device = Device()
device.identify.send('test')
A few notes: I renamed outer_send to _send, as I assume you don't want people calling that directly on the Device object - if you do, just rename it send and it still works; the error bit seemed superfluous, so left it out; your outer_send was missing self as a parameter - it doesn't need it, but if you do want to leave it out, annotate the method with #staticmethod to avoid warnings.
I want to call a method from the parent class in a child class.
I use XX.__init__() in my child class and call the press function from the parent class. But it fails when I run the following code:
Func.py
class PC:
def __init__(self):
PCKeyDis = {}
self.PCKeyDis = PCKeyDis
def Press(self,key):
KeyDis = self.PCKeyDis
if len(key)==1 and key.islower():
key = key.upper()
win32api.keybd_event(KeyDis[key],0,0,0)
time.sleep(0.1)
win32api.keybd_event(KeyDis[key],0,win32con.KEYEVENTF_KEYUP,0)
class PCFunc(PC):
def __init__(self):
pass
def Sentence(self,string):
PC.__init__()
strlist = list(string)
for i in xrange(len(strlist)):
if strlist[i] == ' ':
strlist[i] = 'Space'
PC.Press(strlist[i]) #use this function
action.py
import Func
import win32gui
PC = Func.PC()
PCFunc = Func.PCFunc ()
win32gui.SetForegroundWindow(win32gui.FindWindow(winclass,winnm))
PCFunc.Sentence(path)
I get:
unbound method Sentence() must be called with PCFunc instance as first argument (got str instance instead)
If you want to call the constructor of the base class, then you do it on instantiation in the __init__() method, not in the Sentence() method:
def __init__(self):
super(self.__class__, self).__init__()
Since Sentence() is an instance method, you need to call it via an instance of the class (like the error tells you):
pc_func = PCFunc()
pc_func.Sentence(var)
Here you are calling the method with an undefined variable:
PCFunc.Sentence(path)
Instead you need to give a string as parameter, so either write Sentence('path'), or define the variable first:
path = 'my path'
pc_func.Sentence(path)
Do not use the same name as the class name for an instance of the class:
PCFunc = Func.PCFunc ()
Otherwise the variable name storing the instance overwrites the class name.
Apart from that, it is unclear what your code is actually supposed to do. Have a look at the Python code conventions for a first step to making your code more readible. Then do some research about classes and inheritance.
The code you posted does not produce the error you posted. Here is an example that will produce that error:
class Dog:
def do_stuff(self, string):
print string
d = Dog()
d.do_stuff('hello')
Dog.do_stuff(d, 'goodbye')
Dog.do_stuff('goodbye')
--output:--
hello
goodbye
Traceback (most recent call last):
File "1.py", line 9, in <module>
Dog.do_stuff('goodbye')
TypeError: unbound method do_stuff() must be called with Dog instance as first argument (got str instance instead)
An __init__() function can also produce that error:
class Dog:
def __init__(self):
pass
def do_stuff(self, string):
print(string)
Dog.__init__()
--output:--
Traceback (most recent call last):
File "1.py", line 7, in <module>
Dog.__init__()
TypeError: unbound method __init__() must be called with Dog instance as first argument (got nothing instead)
In the line:
d.do_stuff('hello')
the fragment d.do_stuff causes python to create and return a bound method object--which is then immediately executed by the function execution operator () in the fragment ('hello’). The bound method is bound to the instance d, hence the reason it is called a bound method. A bound method automatically passes the instance it contains to the method when the method is executed.
On the other hand, when you write:
Dog.do_stuff(....)
the fragment Dog.do_stuff causes python to create and return an unbound method. An unbound method does not contain an instance, so when an unbound method is executed by the function execution operator (), you must manually pass an instance. (In python3, things changed and you can pass anything as the first argument--an instance of the class isn't required.)
This question already has an answer here:
Python: NameError: global name 'foobar' is not defined [duplicate]
(1 answer)
Closed 7 years ago.
I am getting the following Name Error in my python program though I declared the function before it is used.
Here is my program:
def __init__(self):
self.root = None
def insert_at(leaf, value):
#some code here....
def insert(self,value):
#some code here....
insert_at(self.root, value)
def main():
#some code here
insert(10)
#some code here
Here is my error:
File "programs/binary_tree.py", line 38, in insert
insert_at(self.root, value)
NameError: name 'insert_at' is not defined
I did go through the following questions before asking this question, but couldn't understand why I am getting the error.
Make function definition in a python file order independent
and
Python NameError: name is not defined
Looks like those are methods in a class. You need the following changes:
def insert_at(self, leaf, value): # add self
self.insert_at(self.root, value) # add self
Hello I'm having trouble with the __str__ when I try to print my object. The interpreter is telling me "TypeError: not enough arguments for format string"
This is the code that I'm trying to run!
'My Practice Class'
class Directory:
'A Simple Directory Class'
def __init__(self, name, parent):
self.name = name
self.parent = parent
def __str__(self):
return 'I am %s a Child directory of %s' % (self.name, self.parent)
def __repr__(self):
return 'Directory(%r)' % self.name
print a
Traceback (most recent call last):
File "<\stdin>", line 1, in <\module>
File "myclass.py", line 14, in \__str\__
def \__repr\__(self):
TypeError: not enough arguments for format string
Thank you
[Moved from comments as this might be a helpful sign post question]
If you are importing a module that you are working on calling
import xxx
a second time does not re-import the changed file (python is trying to be clever, sees you already have that module loaded short-circuts the process). What was going on was that you were changing the file, but python was never seeing those changes.
To reload a module call
reload(xxx)
Also becareful if you imported things as
from xxx import yyy
Calling reload xxx will not affect yyy you would need to do
reload(xxx)
yyy = xxx.yyy
Seems to work fine for me:
>>> class Directory:
'A Simple Directory Class'
def __init__(self, name, parent):
self.name = name
self.parent = parent
def __str__(self):
return 'I am %s a Child directory of %s' % (self.name, self.parent)
def __repr__(self):
return 'Directory(%r)' % self.name
>>> a = Directory('Name', 'Parent')
>>> print(a)
I am Name a Child directory of Parent
>>>
>>>
This question already has answers here:
Referring to class names through strings?
(5 answers)
Closed 9 years ago.
I have the following variable:
var = 'MyClass'
I would like to create an object of MyClass based on the variable var. Something like var(). How can I do this in Python?
>>> def hello():
... print "hello world"
...
>>> globals()["hello"]()
hello world
Presuming you have the class' module as a variable as well, you can do the following, where the class you want "MyClass" resides in module "my.module":
def get_instance(mod_str, cls_name, *args, **kwargs):
module = __import__(mod_str, fromlist=[cls_name])
mycls = getattr(module, cls_name)
return mycls(*args, **kwargs)
mod_str = 'my.module'
cls_name = 'MyClass'
class_instance = get_instance(mod_str, cls_name, *args, **kwargs)
This function will let you get an instance of any class, with whatever arguments the constructor needs, from any module available to your program.