TypeError: generatecode() takes 0 positional arguments but 1 was given
When you call a method on a class (such as generatecode()
in this case), Python automatically passes self
as the first argument to the function. So when you call self.my_func()
, it's more like calling MyClass.my_func(self)
.
So when Python tells you "generatecode() takes 0 positional arguments but 1 was given", it's telling you that your method is set up to take no arguments, but the self
argument is still being passed when the method is called, so in fact it is receiving one argument.
Adding self
to your method definition should resolve the problem.
def generatecode(self):
pass # Do stuff here
Alternatively, you can make the method static, in which case Python will not pass self
as the first argument:
@staticmethod
def generatecode():
pass # Do stuff here
TypeError: method() takes 0 positional arguments but 1 was given
Several errors are noticed at glance:
- mixture of namespace
You declared list_number
as a global variable, but you cannot set value to it
directly insides a function. Instead, you can let the function return a value,
or use global
statement to temporary allow a function to set a value to
a global variable temperary.
Read more on offical document, or search keyword python namespace
for
relative articles.
- name collision on builtin keyword
Some special word are reserved by python and could not be used as variable or
function name, input
is amoung them.
BTW: The title of your question and example code layout is confusion! Follow the
tour to learn how to ask a better question and improve layout, so that people
can help you out.
Example code: though the test part has some bug I don't solved...
# remove: move it to a main progress for future design
# list_number = list()
# rename: input is a reserved name of builtins, pick another word
def myinput(*pargs):
if pargs:
for arg in pargs:
try:
yield int(arg)
except ValueError:
pass
else:
count = 0
while True:
# move out of `try` statement as it won't raise any exceptions
# imply lowercase for easier string comparison
userinput = input("Enter your number in to list: ").lower()
if userinput in ['quit', 'q']:
# for interactive, give user a response
print("Quit input procedure. Preparing Diagram...")
break
try:
number = int(userinput)
except ValueError:
# raise a error and the output will print to output by default
# there is no need to `print` an error
# and, for improve, you can raise a more specific message
# and continue your program
msg = "The program wants a number as input, please try again.\n"
msg += "Type `Quit` to exit input procedure."
print(msg)
continue
except KeyboardInterrupt:
msg = "You pressed Interrupt Keystroke, program exit."
print(msg)
return 0
# print a message and pass the value intercepted
count += 1
print("%d: number %d is added to queue." % (count, number))
yield number
def diagram(numbers):
# there is no need to iter a list by index
# and I am **not** sure what you want from your origin code
# if what you wnat is:
# join number with "@" sign
# then just use the builtins str.join method
# valid: is_list_like
if is_list_like(numbers):
numstr = map(str, numbers)
ret = "@".join(numstr)
else:
ret = "Nothing to export."
return ret
def is_list_like(obj):
"""fork from pandas.api.types.is_list_like,
search c_is_list_like as keyword"""
return (
# equiv: `isinstance(obj, abc.Iterable)`
hasattr(obj, "__iter__") and not isinstance(obj, type)
# we do not count strings/unicode/bytes as list-like
and not isinstance(obj, (str, bytes))
)
def main(*pargs):
# get a generator of user input
# if passed in values, accept parameter as user input for test
msgout = ""
if pargs:
# bug: test input not filtered by int() function
list_number = list(myinput(pargs))
print("Run builtin test module.")
else:
list_number = list(myinput())
count = len(list_number)
# process your input by whatever means you need
if count == 1:
msgout += "Received %d number from user input.\n" % count
else:
msgout += "Received %d numbers from user input.\n" % count
msgout += "The diagram is:\n%s" % diagram(list_number)
print(msgout)
def test():
"""simulate user input"""
userinputs = [
['a', 1, 5, 4, 9, 'q'],
[999, 'Quit'],
['q'],
]
for userinput in userinputs:
main(*userinput)
# test bug:
# 1. charactor is printed as output, too
if __name__ == "__main__":
# remove test() if you don't need it
test()
main()
Takes 0 positional arguments but 2 were given, when it is not the case
Change to:
def redraw(signum, frame) -> int:
TypeError: start() takes 0 positional arguments but 1 was given
self.start()
is shorthand for writing start(self)
. So you can't pass in a method that's bound to an object, you'll have to pass in a free function (or static method). All methods on a class expects the argument self
(your start
method shouldn't work).
class Example:
def method(self): # Takes `self` as parameter
pass
Instead, you must create a static method that doesn't take any parameters:
class Example:
@staticmethod
def my_static_method():
# Doesn't take `self` as parameter, which means you cannot use
# `self` in this method.
pass
or a free-standing function that's not bound to a class at all.
def my_function():
pass
These can be passed as functions that doesn't take any arguments.
In your specific case, you can make start
a static method, as it doesn't use self
, or a free function:
class MainMenu:
def __init__(self, screen):
pygame.init()
self.screen = screen
def button(self, rect, radius=0, action=None):
click = pygame.mouse.get_pressed()
if rect.collidepoint(pygame.mouse.get_pos()):
color = (141,182,205)
if click[0] == 1 and action != None:
action()
else:
color = (28, 134, 238)
pygame.draw.rect(self.screen, color, rect, border_radius=radius)
def menu(self):
screen_width = self.screen.get_width()
screen_height = self.screen.get_height()
mid_width = screen_width / 2
mid_height = screen_height / 2
btn_start = pygame.Rect(mid_width-150, mid_height*3/5, 300, 100)
# Do this to call the static method.
self.button(btn_start, 50, MainMenu.start)
# Or do this to call the free standing function.
self.button(btn_start, 50, start)
@staticmethod
def start():
return 'start'
def start():
return 'start'
TypeError : takes 0 positional arguments but 1 was given
methods (functions or procedures belonging to a class) require a self
argument , you may be familiar with this
from other languages, (unless explicitly defined as a @staticmethod but it doesn't look like that's what you're going for here) like so:
class myFirst:
def first_func(self): # here
flag=0
phonebook = {
"A" : 938477566,
"B" : 938377264,
"C" : 947662781
}
# testing code
if "A" in phonebook:
flag=1
if "D" not in phonebook:
flag = 0
return flag
myclassObj = myFirst()
status = myclassObj.first_func()
if status > 1:
print ("Pass")
else:
print ("fail")
it should work with that minor change.
if you want to use the @staticmethod
decorator (in case the function doesn't actually require information from the class instance) you would do this instead:
class myFirst:
@staticmethod #here
def first_func():
you can find out more by checking the doc here: https://docs.python.org/3/tutorial/classes.html
Related Topics
How to Set the Text/Value/Content of an 'Entry' Widget Using a Button in Tkinter
Scrapy - Reactor Not Restartable
Improper Use of _New_ to Generate Class Instances
Why Do Some Built-In Python Functions Only Have Pass
How to Modify Variable in Python That Is in Outer, But Not Global, Scope
How to Suppress the Newline After a Print Statement
How to Delete All Blank Lines in the File with the Help of Python
Syntax Error When Using Command Line in Python
Split String into Strings by Length
Remove Non-Numeric Rows in One Column with Pandas
Does Spark Predicate Pushdown Work with Jdbc
Vectorised Haversine Formula with a Pandas Dataframe
On Localhost, How to Pick a Free Port Number
What's the Difference Between Str.Isdigit, Isnumeric and Isdecimal in Python