Here is the method causing the error:
class Kilpailu():
def __init__(self, nimi, pituuskm, osallistujat):
self.nimi = nimi
self.pituuskm = pituuskm
self.osallistujat = osallistujat
def kilpailu_ohi(self):
for i in self.osallistujat:
if (i.getKuljettuMatka>=self.pituuskm):
return True
else:
return False
edit: here is also where getKuljettuMatka is defined
class Auto:
def __init__(self, rekisteritunnus, huippunopeus):
self.rekisteritunnus = rekisteritunnus
self.huippunopeus=huippunopeus
self.nopeus=0
self.KuljettuMatka=0
def getKuljettuMatka(self):
return int(self.KuljettuMatka)
I am trying to call the method that just returns a boolean value and print whether the value is true or false.
class main():
autot = []
for i in range(10):
auto = Auto("ABC-" + str(i + 1), random.randint(100, 200))
autot.append(auto)
k = Kilpailu("Suuri romuralli", 8000, autot)
tunnit = 0
print(k.kilpailu_ohi()) #Should return true/false, instead throws an error
and here is the actual console output for the error
Traceback (most recent call last):
File "/root/PycharmProjects/ohjelmisto1/Harjoitustehtävät/Assosisaatio/autoKilpailu.py", line 51, in <module>
class main():
File "/root/PycharmProjects/ohjelmisto1/Harjoitustehtävät/Assosisaatio/autoKilpailu.py", line 59, in main
print(k.kilpailu_ohi())
File "/root/PycharmProjects/ohjelmisto1/Harjoitustehtävät/Assosisaatio/autoKilpailu.py", line 45, in kilpailu_ohi
if (i.getKuljettuMatka>=self.pituuskm):
TypeError: '>=' not supported between instances of 'method' and 'int'
I have tried changing stuff in the method like variable names in case i was accidentally overwriting something but it didnt work either
def getKuljettuMatka(self): defines .getKuljettuMatka on instances of Auto as a method (that happens to return an integer). You can call the method with i.getKuljettuMatka() (note the parentheses), but what you're doing is comparing the method itself to self.pituuskm, which is an integer, and that doesn't work.
Instead:
def kilpailu_ohi(self):
for i in self.osallistujat:
if (i.getKuljettuMatka() >= self.pituuskm):
return True
else:
return False
By the way, I think the code is a bit roundabout in other ways, but this is you main issue right now.
Related
Traceback (most recent call last):
File "C:\Users\RAC\crypto\...\blockchain.py", line 178, in <module>
blockchain = Blockchain()
^^^^^^^^^^^^
File "C:\Users\RAC\crypto\...\blockchain.py", line 49, in __init__
self.chain = [self.create_genesis_block(0)]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: Blockchain.create_genesis_block() takes 1 positional argument but 2 were given
with code looking like this
class Blockchain:
def __init__(self):
self.chain = [self.create_genesis_block(0)]
self.difficulty = 4
self.nodes = dict()
self.replicated_nodes = dict()
self.coin_ledger = dict()
def create_genesis_block(self):
return Block("Genesis Block", "0", coin)
ive tried adding other arguments but as i am new to this, i havent been able to figure it out myself properly
def create_genesis_block(self): doesn't take a parameter, maybe you meant:
def create_genesis_block(self, block_num):
return Block("Genesis Block", block_num, coin)
or
#staticmethod
def create_genesis_block(block_num):
return Block("Genesis Block", block_num, coin)
when you use the self constructor, you need to initialize the class, try
instanse = Blockchain()
instanse.create_genesis_block()
I'm new to python OOP and I'm struggling with figuring out my error in this code, if anyone can help that would be great!
class Toy:
def __init__(self, price):
self.__price = price
def SetPrice(self, p):
self.__price = p
def GetPrice(self):
return(self.__price)
def InsertionSort(x):
for index in range(1, len(x)):
value = x[index].GetPrice()
i = index -1
while i >= 0:
if value < (x[i].GetPrice()):
x[i+1].SetPrice(x[i])
x[i].SetPrice(value)
i = i -1
else:
break
prices = []
prices.append(Toy(200))
prices.append(Toy(10))
prices.append(Toy(20))
Toy.InsertionSort(prices)
but when I run it I get back this, but I don't really understand what the error means and I've tried writing it other ways but I'm not sure what to do now.
Traceback (most recent call last):
File "C:\Users\USER\AppData\Local\Programs\Python\Python36-32\testId.py",
line 34, in <module>
Toy.InsertionSort(prices)
File "C:\Users\USER\AppData\Local\Programs\Python\Python36-32\testId.py",
line 20, in InsertionSort
if value < (x[i].GetPrice()):
TypeError: '<' not supported between instances of 'int' and 'Toy'
Thank you in advance!
The problem is because the line
x[i+1].SetPrice(x[i])
sets x[i+1] to x[i] which is a Toy, not an int.
I'm implementing something in python, specifically a cmp method for a class, here it is:
def __cmp__(self, other):
if self.time < other.get_time():
return -1
if self.time > other.get_time():
return 1
if self.type == A and other.get_type() == D:
return -1
if self.type == D and other.get_type() == A:
return 1
if self.person < other.get_person():
return -1
if self.person > other.get_person():
return 1
return 0
and I get this error when running the program:
Traceback (most recent call last):
File "wp-proj03.py", line 292, in <module>
main()
File "wp-proj03.py", line 180, in main
events.put(e)
File "/usr/lib/python2.7/Queue.py", line 136, in put
self._put(item)
File "/usr/lib/python2.7/Queue.py", line 225, in _put
heappush(self.queue, item)
TypeError: comparison did not return an int
as you can see, I am using a queue, specifically a priority-queue (from the built-in Queue.py module). When i try to put an instance of my class into the queue, it throws this error.
Can someone tell me what is the problem with my comparison method? or could it be a problem somewhere else?
thx
Probably, due to the indentation problem mentioned by other commenters, your cmp function does not actually include the final return statement, and so in the case self.time == other.get_time(), None is returned (a default return value for a function exiting without an explicit return) instead of an integer that is expected as the result of __cmp__.
I've just been reading an article that talks about implementing a parser in python:
http://effbot.org/zone/simple-top-down-parsing.htm
The general idea behind the code is described in this paper: http://mauke.hopto.org/stuff/papers/p41-pratt.pdf
Being fairly new to writing parsers in python so I'm trying to write something similar as a learning exercise. However when I attempted to try to code up something similar to what was found in the article I am getting an TypeError: unbound method TypeError. This is the first time I've encountered such an error and I've spent all day trying to figure this out but I haven't solved the issue. Here is a minimal code example (in it's entirety) that has this problem:
import re
class Symbol_base(object):
""" A base class for all symbols"""
id = None # node/token type name
value = None #used by literals
first = second = third = None #used by tree nodes
def nud(self):
""" A default implementation for nud """
raise SyntaxError("Syntax error (%r)." % self.id)
def led(self,left):
""" A default implementation for led """
raise SyntaxError("Unknown operator (%r)." % self.id)
def __repr__(self):
if self.id == "(name)" or self.id == "(literal)":
return "(%s %s)" % (self.id[1:-1], self.value)
out = [self.id, self.first, self.second, self.third]
out = map(str, filter(None,out))
return "(" + " ".join(out) + ")"
symbol_table = {}
def symbol(id, bindingpower=0):
""" If a given symbol is found in the symbol_table return it.
If the symblo cannot be found theni create the appropriate class
and add that to the symbol_table."""
try:
s = symbol_table[id]
except KeyError:
class s(Symbol_base):
pass
s.__name__ = "symbol:" + id #for debugging purposes
s.id = id
s.lbp = bindingpower
symbol_table[id] = s
else:
s.lbp = max(bindingpower,s.lbp)
return s
def infix(id, bp):
""" Helper function for defining the symbols for infix operations """
def infix_led(self, left):
self.first = left
self.second = expression(bp)
return self
symbol(id, bp).led = infix_led
#define all the symbols
infix("+", 10)
symbol("(literal)").nud = lambda self: self #literal values must return the symbol itself
symbol("(end)")
token_pat = re.compile("\s*(?:(\d+)|(.))")
def tokenize(program):
for number, operator in token_pat.findall(program):
if number:
symbol = symbol_table["(literal)"]
s = symbol()
s.value = number
yield s
else:
symbol = symbol_table.get(operator)
if not symbol:
raise SyntaxError("Unknown operator")
yield symbol
symbol = symbol_table["(end)"]
yield symbol()
def expression(rbp = 0):
global token
t = token
token = next()
left = t.nud()
while rbp < token.lbp:
t = token
token = next()
left = t.led(left)
return left
def parse(program):
global token, next
next = tokenize(program).next
token = next()
return expression()
def __main__():
print parse("1 + 2")
if __name__ == "__main__":
__main__()
When I try to run this with pypy:
Traceback (most recent call last):
File "app_main.py", line 72, in run_toplevel
File "parser_code_issue.py", line 93, in <module>
__main__()
File "parser_code_issue.py", line 90, in __main__
print parse("1 + 2")
File "parser_code_issue.py", line 87, in parse
return expression()
File "parser_code_issue.py", line 81, in expression
left = t.led(left)
TypeError: unbound method infix_led() must be called with symbol:+ instance as first argument (got symbol:(literal) instance instead)
I'm guessing this happens because I don't create an instance for the infix operations but I'm not really wanting to create an instance at that point. Is there some way I can change those methods without creating instances?
Any help explaining why this is happening and what I can do to fix the code is greatly appreciated!
Also is this behaviour going to change in python 3?
You forgot to create an instance of the symbol in your tokenize() function; when not a number, yield symbol(), not symbol:
else:
symbol = symbol_table.get(operator)
if not symbol:
raise SyntaxError("Unknown operator")
yield symbol()
With that one change your code prints:
(+ (literal 1) (literal 2))
You haven't bound new function to the instance of your object.
import types
obj = symbol(id, bp)
obj.led = types.MethodType(infix_led, obj)
See accepted answer to another SO question
What is the error below? Also, is there a better way to implement the following classes?
#!/usr/bin/python
class Datacenters:
def __init__(self,name,location,cpu,mem):
self.name=name
self.location=location
self.cpu=cpu
self.mem=mem
def getparam(self):
return self.name,self.location ,self.cpu,self.mem
def getname(self):
return self.name
class WS(Datacenters):
def __init__(self,name,location,cpu,mem,obj):
#datacentername = Datacenters.__init__(self) #To which data center it is associated
self.dcname =obj.name #To which data center it is associated
Datacenters.__init__(obj,name,location,cpu,mem)
def getparam(self,obj):
self.name,self.location ,self.cpu,self.mem = obj.getparam()
print self.dcname
#return self.name,self.location ,self.cpu,self.mem,obj.name
def getwsname(self):
return self.name
class Pcs(WS):
def __init__(self,name,location,cpu,mem,obj):
self.wsname = obj.getwsname() #To which WS it is associated
WS.__init__(obj,name,location,cpu,mem)
def getparam(self,obj):
print obj.getparam()
print self.wsname
a = Datacenters("dc1","Bl1",20,30)
print a.getparam()
b = WS("WS1","Bl1",21,31,a)
print b.getparam(a)
c = Pcs("PC1","Bl1",20,30,b)
#print c.getparam(b)
output:
Press ENTER or type command to continue
('dc1', 'Bl1', 20, 30)
dc1
None
Traceback (most recent call last):
File "class1.py", line 45, in <module>
c = Pcs("PC1","Bl1",20,30,b)
File "class1.py", line 34, in __init__
WS.__init__(obj,name,location,cpu,mem)
TypeError: __init__() takes exactly 6 arguments (5 given)
The error is that you pass in five arguments, but the __init__ needs six. Count them:
def __init__(self,name,location,cpu,mem,obj):
Six arguments. You call it like so:
WS.__init__(obj,name,location,cpu,mem)
Five arguments. The first one, self is missing. What you should ask yourself is why you don't have to pass in six arguments all the time.
And that is because self is passed in automatically when you call the method on an instance. However, in this case you don't call it on an instance, you call it directly on the class. There is of course no need to do so in this case, the correct syntax is:
WS(obj,name,location,cpu,mem)
As you indeed above note works further up.