"'int' object has no attribute 'getal'" in self made class Python - python

The idea of the program is to take a "language" and turn it into numbers. The language is build quite easy
K = 10
P = 20
T = 40
V = 80
anything smaller then 10 will be represented in normal numbers
Now the numbers shouldn't be something to worry about I explain this so it's easier to get what I try to achieve here.
I build up a class called "Mangarevaans" which looks as following:
def mag2arab(getal): #this function is designed to turn the letters into the normal numbers we're used to
mag = str(getal)
waarde = {"K": 10, "P": 20, "T": 40, "V": 80}
arab = 0
for index, j in enumerate(mag):
if index == 0 and j.isnumeric():
if len(getal) == 1:
x = 0
else:
x = 1
arab += int(j) * waarde[mag[x]]
elif j.isnumeric():
arab += int(j)
elif not (str(mag[0]).isnumeric() and index == 1):
arab += waarde[j]
return arab
class Mangarevaans():
"""
>>>612 // Mangarevaans(26)
Mangarevaans('P3')
"""
def __init__(self, getal):
if isinstance(getal, int):
assert 1 <= getal < 799, 'ongeldige waarde' #this is one of the rules of the language that if there is a number it should be between these values
self.getal = getal
else:
for letter in getal:
if isinstance(getal, str):
for letter in getal:
if letter in "VTPK":
self.getal = getal
else:
raise AssertionError('ongeldige waarde')
self.getal = mag2arab(getal)
def __int__(self):
return self.getal
def __str__(self):
return arab2mag(self.getal)
def __repr__(self):
return f"Mangarevaans('{str(arab2mag(self.getal))}')"
def __rfloordiv__(other, self):
return Mangarevaans(other // self.getal) #The problem occurs here
Now when I want to run the doctest
"""
>>>612 // Mangarevaans(26)
Mangarevaans('P3')
"""
I get an error saying
'int' object has no attribute 'getal'
but if I change my self to a string I get
'str' object has no attribute 'getal'
how can i define if the attribute "getal" belongs with "str" or "int" ?
Can anyone help me ?
Thanks a lot already

self is always the first argument, even in the r* (right) methods. So write:
def __rfloordiv__(self, other):
return Mangarevaans(other // self.getal)
instead of:
def __rfloordiv__(other, self):
return Mangarevaans(other // self.getal)

Related

class self acts like integer

I didn't understand why. And It will raise an error 'int' object has no attribute 'v', but I want to access the self.v. When I print only self it will print some numbers. I couldn't understand what was going on. Here is my code.
class Candidate:
def __init__(self,val,pscore,nscore):
self.v = val
self.p = pscore
self.n = nscore
def __str__(self):
return f"{self.v} ({self.p},{self.n})"
def check_plus_pos(self, guessval):
count = 0
b = self.v
a = str(b)
guessval = str(guessval)
for i in range(0,len(a)):
if a[i] == guessval[i]:
count += 1
return count
def check_neg_pos(self, guessval):
count = 0
b = self.v
a = str(b)
guessval = str(guessval)
for i in range(0,len(a)):
for j in range(0,len(guessval)):
if a[i] == guessval[j] and a[i] != guessval[i]:
count += 1
return count
def consistent(self, guess):
if Candidate.check_plus_pos(self,guess.v) == guess.p and Candidate.check_neg_pos(self,guess.v) == guess.n:
return True
else:
return False
The problem occurs at b == self.v I wanted to assign the self.v value to a variable.
To be honest it's pretty hard to understand what that code/class is supposed to do, imho it needs some serious refactoring.
My guess is you should:
instantiate your class somewhere
use the method as an instance method, so invoke it with self and not the class name
do NOT pass self explicitly at all
do NOT use abbreviations which are not commonly known
do NOT use single letter variables a means literally nothing
use docstrings for non-trivial functions (or as a rule of thumb to most of functions/methods)
use type hints, which will help you catch this kind of errors automatically (if you configure your IDE that is)
get rid of the assignment to b at all, it's not reused and doesn't seem do anything. This will do the same a = str(self.v)
... # all the class related code above
def check_neg_pos(self, guessval):
count = 0
a = str(self.v)
guessval = str(guessval)
for i in range(0,len(a)):
for j in range(0,len(guessval)):
if a[i] == guessval[j] and a[i] != guessval[i]:
count += 1
return count
def is_consistent(self, guess: Candidate)->bool:
return bool(self.check_plus_pos(guess.v) == guess.p and self.check_neg_pos(guess.v) == guess.n)
# Example usage
candidate_1 = Candidate(1,2,3)
candidate_2 = Candidate(4,5,6)
candidates_consistent = candidate_1.is_consistent(guess=candidate_2)
print(candidates_consistent)

'int' object not callable heap sort function

'int' Object Not Callable Heap Sort Function
Im trying to create a function that return a sorted list but im getting the following error: "new_value = sort_heap.deleteMin() 'int' object is not callable"
This is the code:
class MinHeap:
def __init__(self):
self.heap=[]
def __str__(self):
return f'{self.heap}'
__repr__=__str__
def parent(self,index):
# -- YOUR CODE STARTS HERE
if index>len(self) or index<=1:
return None
else:
return self.heap[index//2-1]
def leftChild(self,index):
# -- YOUR CODE STARTS HERE
if index<1 or 2*index>len(self):
return None
else:
return self.heap[2*index-1]
def rightChild(self,index):
if index<1 or 2*index>len(self):
return None
else:
return self.heap[2*index-1]
def __len__(self):
return len(self.heap)
def insert(self,x):
self.heap.append(x)
current = len(self)
while self.parent(current) is not None and self.parent(current)>x:
self.heap[current-1], self.heap[current//2-1] = self.heap[current//2-1], self.heap[current-1]
current = current//2
#property
def deleteMin(self):
if len(self)==0:
return None
elif len(self)==1:
out=self.heap[0]
self.heap=[]
return out
deleted = self.heap[0]
current = 1
self.heap[0] = self.heap[len(self)-1]
x = self.heap.pop()
moved_value = self.heap[0]
while self.leftChild(current) is not None:
left=self.leftChild(current)
right=self.rightChild(current)
if right is not None:
if left<=right and left<moved_value:
self.heap[current-1], self.heap[current*2] = self.heap[current*2], self.heap[current-1]
current = current *2
elif left>right and right<moved_value:
self.heap[current-1], self.heap[current*2] = self.heap[current*2], self.heap[current-1]
current = (current*2) + 1
else:
break
else:
if left<moved_value:
self.heap[current-1], self.heap[(current*2)-1] = self.heap[(current*2)-1], self.heap[current-1]
current = current*2
else:
break
return deleted
def heapSort(numList):
'''
>>> heapSort([9,7,4,1,2,4,8,7,0,-1])
[-1, 0, 1, 2, 4, 4, 7, 7, 8, 9]
'''
sort_heap = MinHeap()
for i in range (len(numList)):
sort_heap.insert(numList[i])
sortedList= []
lenght=len(numList)
while lenght >0:
new_value = sort_heap.deleteMin()
sortedList.append(new_value)
lenght -= 1
return sortedList
The MinHeap class is a given but I'm allow to modify it. Could Someone please help? Thanks
Seeing your (btw wrong formatted code, please redo the formatting) code I can see, that deleteMin is a #property and not a class method. Therefore you shuld write:
new_value = sort_heap.deleteMin
# ^ You see, no brackets here

'int' object is not callable error in class

In python 2.7, I am writing a class called Zillion, which is to act as a counter for very large integers. I believe I have it riddled out, but I keep running into TypeError: 'int' object is not callable , which seems to mean that at some point in my code I tried to call an int like it was a function. Many of the examples I found on this site were simply a mathematical error where the writer omitted an operator. I can't seem to find my error.
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
z.increment()
TypeError: 'int' object is not callable
My code:
class Zillion:
def __init__(self, digits):
self.new = []
self.count = 0 # for use in process and increment
self.increment = 1 # for use in increment
def process(self, digits):
if digits == '':
raise RuntimeError
elif digits[0].isdigit() == False:
if digits[0] == ' ' or digits[0] == ',':
digits = digits[1:]
else:
raise RuntimeError
elif digits[0].isdigit():
self.new.append(int(digits[0]))
digits = digits[1:]
self.count += 1
if digits != '':
process(self, digits)
process(self, digits)
if self.count == 0:
raise RuntimeError
self.new2 = self.new # for use in isZero
def toString(self):
self.mystring =''
self.x = 0
while self.x < self.count:
self.mystring = self.mystring + str(self.new[self.x])
self.x += 1
print(self.mystring)
def isZero(self):
if self.new2[0] != '0':
return False
elif self.new2[0] == '0':
self.new2 = self.new2[1:]
isZero(self)
return True
def increment(self):
if self.new[self.count - self.increment] == 9:
self.new[self.count - self.increment] = 0
if isZero(self):
self.count += 1
self.new= [1] + self.new
else:
self.increment += 1
increment(self)
elif self.new[self.count - self.increment] != 9:
self.new[self.count - self.increment] = self.new[self.count - self.increment] + 1
You have both an instance variable and a method named increment that seems to be your problem with that traceback at least.
in __init__ you define self.increment = 1 and that masks the method with the same name
To fix, just rename one of them (and if it's the variable name, make sure you change all the places that use it--like throughout the increment method)
One way to see what's happening here is to use type to investigate. For example:
>>> type(Zillion.increment)
<type 'instancemethod'>
>>> z = Zillion('5')
>>> type(z.incremenet)
<type 'int'>
You have defined an instance variable in Zillion.__init__()
def __init__(self, digits):
self.new = []
self.count = 0
self.increment = 1 # Here!
Then you defined a method with the same name 'Zillion.increment()`:
def increment(self):
[…]
So if you try to call your method like this:
big_number = Zillion()
big_number.increment()
.ìncrement will be the integer you have defined in .__init__() and not the method.
Because you have a variable member self.increment,and it has been set to the 1 in your __init__ function.
z.increment represents the variable member which set to 1.
You can rename your function from increment to the _increment(or any other names), and it will works.

Python - Classes - Self Not Defined

Below I'm attempting to make a simple Keygen as a first project. Somewhere I'm getting the error the Self has not been defined.
I'm guessing it's probably something easy
import random
class KeyGenerator():
def __init__(self):
length = 0
counter = 0
key = []
Letters = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
def KeyGen4(self):
while self.counter != self.length:
a = random.choice(self.Letters)
print a #test
r = (random.randint(0,1))
print r #test
if r == True:
a = a.upper()
else:
pass
self.key.append(a)
self.counter += 1
s = ''
self.key = s.join(key)
print self.key
return self.key
def start(self):
selection = raw_input('[K]eygen4, [C]ustom length Keygen or [N]umbers? >')
if selection == 'K' or 'k':
length = 4
keyGen4(self)
elif selection == 'N' or 'n':
KeyGenN(self)
elif selection == 'C' or 'c':
length = int(raw_input("Key Length: "))
#KeyGen4(self) # Change later after creating method with more options
start(self)
Your indention is wrong, but I assume this is only a copy-pasting issue.
That start(self) at the bottom doesn't make sense,
and indeed self is not defined there. You should create an instance of the class, and then call its start method:
KeyGenerator().start()
# or
key_gen = KeyGenerator()
key_gen.start()
You have two problems:
you miss indentation on every class-function
you must create an object of the class before you can call any of its functions
Your class should look like this
import random
class KeyGenerator():
def __init__(self):
length = 0
counter = 0
key = []
Letters = ['a','b','c','d','e']
def KeyGen4(self):
while self.counter != self.length:
a = random.choice(self.Letters)
print a #test
r = (random.randint(0,1))
print r #test
if r == True:
a = a.upper()
else:
pass
self.key.append(a)
self.counter += 1
s = ''
self.key = s.join(key)
print self.key
return self.key
def start(self):
selection = raw_input('[K]eygen4, [C]ustom length Keygen or [N]umbers? >')
if selection == 'K' or 'k':
length = 4
self.keyGen4()
elif selection == 'N' or 'n':
self.KeyGenN()
elif selection == 'C' or 'c':
length = int(raw_input("Key Length: "))
#KeyGen4(self) # Change later after creating method with more options
#now make an instance of your class
my_key_gen = KeyGenerator()
my_key_gen.start()
Please note that when calling class functions inside the class, you need to use self.FUNCNAME. All class functions should take "self" as argument. If that is their only argument then you simply call them with self.func(). If they take arguments you still ommit the self, as self.func(arg1, arg2)

Calling a method from the same class

I'm writing a class for a simple game of 4 in a row, but I'm running into a problem calling a method in the same class. Here's the whole class for the sake of completeness:
class Grid:
grid = None
# creates a new empty 10 x 10 grid
def reset():
Grid.grid = [[0] * 10 for i in range(10)]
# places an X or O
def place(player,x,y):
Grid.grid[x][y] = player
# returns the element in the grid
def getAt(x,y):
return Grid.grid[x][y]
# checks for wins in a certain direction
def checkLine(player,v,count,x,y):
x = x+v[0]
y = y+v[1]
if x < 0 or x > 9:
return
if y < 0 or y > 9:
return
if Grid.grid[x][y] == p:
count = count+1
if count == 4:
return True
checkLine(player,v,count,x,y)
return False
# returns the number of the player that won
def check():
i = 'i'
for x in range(0,10):
for y in range(0,10):
if Grid.grid[x][y] > 0:
p = Grid.grid[x][y]
f = checkLine(p,0,array(i,[1,0]),x,y)
if f:
return p
f = checkLine(p,0,array(i,[0,1]),x,y)
if f:
return p
f = checkLine(p,0,array(i,[1,1]),x,y)
if f:
return p
f = checkLine(p,0,array(i,[-1,0]),x,y)
if f:
return p
f = checkLine(p,0,array(i,[0,-1]),x,y)
if f:
return p
f = checkLine(p,0,array(i,[-1,-1]),x,y)
if f:
return p
f = checkLine(p,0,array(i,[1,-1]),x,y)
if f:
return p
f = checkLine(p,0,array(i,[-1,1]),x,y)
if f:
return p
return 0
reset = staticmethod(reset)
place = staticmethod(place)
getAt = staticmethod(getAt)
check = staticmethod(check)
checkLine = staticmethod(checkLine)
I'm trying to call checkLine() from check(), but I get the error "NameError: global name 'checkLine' is not defined". When I call Grid.checkLine() instead, I get "TypeError: 'module' object is not callable"
How do I call checkLine()?
EDIT:
#beer_monk
class Grid(object):
grid = None
# creates a new empty 10 x 10 grid
def reset(self):
Grid.grid = [[0] * 10 for i in range(10)]
# places an X or O
def place(self,player,x,y):
Grid.grid[x][y] = player
# returns the element in the grid
def getAt(self,x,y):
return Grid.grid[x][y]
# checks for wins in a certain direction
def checkLine(self,player,v,count,x,y):
x = x+v[0]
y = y+v[1]
if x < 0 or x > 9:
return
if y < 0 or y > 9:
return
if Grid.grid[x][y] == p:
count = count+1
if count == 4:
return True
checkLine(self,player,v,count,x,y)
return False
# returns the number of the player that won
def check(self):
i = 'i'
for x in range(0,10):
for y in range(0,10):
if Grid.grid[x][y] > 0:
p = Grid.grid[x][y]
for vx in range(-1,2):
for vy in range(-1,2):
f = self.checkLine(p,0,array(i,[vx,vy]),x,y)
if f:
return p
return 0
reset = staticmethod(reset)
place = staticmethod(place)
getAt = staticmethod(getAt)
check = staticmethod(check)
checkLine = staticmethod(checkLine)
Get rid of the class. Use plain functions and module level variable for grid.
The class is not helping you in any way.
PS. If you really want to call checkline from within the class, you'd call Grid.checkline. For example:
class Foo:
#staticmethod
def test():
print('Hi')
#staticmethod
def test2():
Foo.test()
Foo.test2()
prints
Hi
Syntax:
class_Name.function_Name(self)
Example:
Turn.checkHoriz(self)
A reworked example (hopefully showing a better use of classes!)
import itertools
try:
rng = xrange # Python 2.x
except NameError:
rng = range # Python 3.x
class Turn(object):
def __init__(self, players):
self.players = itertools.cycle(players)
self.next()
def __call__(self):
return self.now
def next(self):
self.now = self.players.next()
class Grid(object):
EMPTY = ' '
WIDTH = 10
HEIGHT = 10
WINLENGTH = 4
def __init__(self, debug=False):
self.debug = debug
self.grid = [Grid.EMPTY*Grid.WIDTH for i in rng(Grid.HEIGHT)]
self.player = Turn(['X','O'])
def set(self, x, y):
if self.grid[y][x]==Grid.EMPTY:
t = self.grid[y]
self.grid[y] = t[:x] + self.player() + t[x+1:]
self.player.next()
else:
raise ValueError('({0},{1}) is already taken'.format(x,y))
def get(self, x, y):
return self.grid[y][x]
def __str__(self):
corner = '+'
hor = '='
ver = '|'
res = [corner + hor*Grid.WIDTH + corner]
for row in self.grid[::-1]:
res.append(ver + row + ver)
res.append(corner + hor*Grid.WIDTH + corner)
return '\n'.join(res)
def _check(self, s):
if self.debug: print("Check '{0}'".format(s))
# Exercise left to you!
# See if a winning string exists in s
# If so, return winning player char; else False
return False
def _checkVert(self):
if self.debug: print("Check verticals")
for x in rng(Grid.WIDTH):
winner = self._check([self.get(x,y) for y in rng(Grid.HEIGHT)])
if winner:
return winner
return False
def _checkHoriz(self):
if self.debug: print("Check horizontals")
for y in rng(Grid.HEIGHT):
winner = self._check([self.get(x,y) for x in rng(Grid.WIDTH)])
if winner:
return winner
return False
def _checkUpdiag(self):
if self.debug: print("Check up-diagonals")
for y in rng(Grid.HEIGHT-Grid.WINLENGTH+1):
winner = self._check([self.get(d,y+d) for d in rng(min(Grid.HEIGHT-y, Grid.WIDTH))])
if winner:
return winner
for x in rng(1, Grid.WIDTH-Grid.WINLENGTH+1):
winner = self._check([self.get(x+d,d) for d in rng(min(Grid.WIDTH-x, Grid.HEIGHT))])
if winner:
return winner
return False
def _checkDowndiag(self):
if self.debug: print("Check down-diagonals")
for y in rng(Grid.WINLENGTH-1, Grid.HEIGHT):
winner = self._check([self.get(d,y-d) for d in rng(min(y+1, Grid.WIDTH))])
if winner:
return winner
for x in rng(1, Grid.WIDTH-Grid.WINLENGTH+1):
winner = self._check([self.get(x+d,d) for d in rng(min(Grid.WIDTH-x, Grid.HEIGHT))])
if winner:
return winner
return False
def isWin(self):
"Return winning player or False"
return self._checkVert() or self._checkHoriz() or self._checkUpdiag() or self._checkDowndiag()
def test():
g = Grid()
for o in rng(Grid.WIDTH-1):
g.set(0,o)
g.set(Grid.WIDTH-1-o,0)
g.set(Grid.WIDTH-1,Grid.HEIGHT-1-o)
g.set(o,Grid.HEIGHT-1)
print(g)
return g
g = test()
print g.isWin()
Unlike java or c++, in python all class methods must accept the class instance as the first variable. In pretty much every single python code ive seen, the object is referred to as self. For example:
def reset(self):
self.grid = [[0] * 10 for i in range(10)]
See http://docs.python.org/tutorial/classes.html
Note that in other languages, the translation is made automatically
There are multiple problems in your class definition. You have not defined array which you are using in your code. Also in the checkLine call you are sending a int, and in its definition you are trying to subscript it. Leaving those aside, I hope you realize that you are using staticmethods for all your class methods here. In that case, whenever you are caling your methods within your class, you still need to call them via your class's class object. So, within your class, when you are calling checkLine, call it is as Grid.checkLine That should resolve your NameError problem.
Also, it looks like there is some problem with your module imports. You might have imported a Module by name Grid and you have having a class called Grid here too. That Python is thinking that you are calling your imported modules Grid method,which is not callable. (I think,there is not a full-picture available here to see why the TypeError is resulting)
The best way to resolve the problem, use Classes as they are best used, namely create objects and call methods on those objects. Also use proper namespaces. And for all these you may start with some good introductory material, like Python tutorial.
Instead of operating on an object, you are actually modifying the class itself. Python lets you do that, but it's not really what classes are for. So you run into a couple problems
-You will never be able to make multiple Grids this way
the Grid can't refer back to itself and e.g. call checkLine
After your grid definition, try instantiating your grid and calling methods on it like this
aGrid = Grid()
...
aGrid.checkLine()
To do that you, you first need to modify all of the method definitions to take "self" as your first variable and in check, call self.checkLine()
def check(self):
...
self.checkLine()
...
Also, your repeated checking cries out for a FOR loop. You don't need to write out the cases.
Java programmer as well here, here is how I got it to call an internal method:
class Foo:
variable = 0
def test(self):
self.variable = 'Hi'
print(self.variable)
def test2(self):
Foo.test(self)
tmp = Foo()
tmp.test2()

Categories