The perfect, but impossible, scenario would be:
class example(object):
def __init__(self,x,y):
self.x = x
self.y = y
def foo(self, x = self.x, y = self.y):
return x + y
It doesn't work because self isn't defined. I have done lots of research, looked on decorators, descriptors, metaclasses, almost everything. The solution may be the most obvious and known to all, but I couldn't find it. I could manage two workarounds, as follows:
def prep(argslist, argsprovided, attributes):
argsout = []
for name in argslist:
if name in argsprovided:
argsout.append(argsprovided[name])
else:
argsout.append(getattr(attributes,name))
return argsout
class example(object):
# I can create a default instance or a custom one
def __init__(self,x = 1,y = 1,z = 1,w = 1):
self.x = x
self.y = y
self.z = z
self.w = w
# I can wrap a function to use the self argument
def wrapper(self):
def foo(x = self.x, y = self.y, z = self.z, w = self.w):
return x + y + z + w
return foo
# I can wrap 'joo' alongside with foo, and make 'wrapper' return a list
def joo(self, **kwargs):
[x,y,z,w] = prep(['x','y','z','w'],kwargs,self)
return x + y + z + 2*w
# I can use my custom 'prep' function to to the job
def foo(self, **kwargs):
[x,y,z,w] = prep(['x','y','z','w'],kwargs,self)
return x + y + z + w
# Creates a default instance and a custom one
c = example()
d = example(2,2,2,2)
# I can use 'foo' with the instance's default values with both wrapping and 'prepping'
print(c.wrapper()())
print(d.wrapper()())
print(c.foo())
print(d.foo())
# I can use 'foo' with a mix of default values and provided values with both wrapping and 'prepping'
print(c.wrapper()(1,2,3))
print(d.wrapper()(1,2,3))
print(c.foo(y = 3,z = 4,w = 5))
print(d.foo(y = 3,z = 4,w = 5))
The code prints out:
4
8
4
8
7
8
13
14
I have a huge class with lots of functions, every one needs the behavior of 'foo'. My prep solution is too time consuming. After profiling the code, I figured it spent 12 seconds inside prep only. What is a clever and less time consuming way of doing this? I'm completely lost.
I'm not sure it will help but how about using None as a default value and use a clause to determine the value. For example:
def foo(self, x=None, y=None):
real_x = x if x != None else self.x
real_y = y if y != None else self.y
return real_x + real_y
I found six ways of doing what I wanted. After profiling the code, the result was:
afoo foo noo1 noo2 wrap1 wrap2
6.730 28.507 3.98 4.097 10.256 3.468
6.407 28.659 4.096 3.924 9.783 3.529
6.277 28.450 3.946 3.889 10.265 3.685
6.531 30.287 3.964 4.149 10.077 3.674
As you will see ahead, noo1, noo2 and wap2 are quite similar on code. The conventional method afoo is not that efficient. My custom method foo is terrible and wrap1 was just tested for the sake of completeness.
afoo.py
The drawback is that you need an extra line for each function argument.
class example(object):
# I can create a default class or a custom one
def __init__(self,x = 1,y = 1,z = 1,w = 1):
self.x = x
self.y = y
self.z = z
self.w = w
def afoo(self, x = None, y = None, z = None, w = None):
x = x if x != None else self.x
y = y if y != None else self.y
z = z if z != None else self.z
w = w if w != None else self.w
return x + y + z + w
c = example(2,2,2,2)
for i in range(0, 10000000):
c.afoo(1,2,3,4)
foo.py
This one is the slower method.
def prep(argslist, argsprovided, attributes):
argsout = []
for name in argslist:
if name in argsprovided:
argsout.append(argsprovided[name])
else:
argsout.append(getattr(attributes,name))
return argsout
class example(object):
# I can create a default class or a custom one
def __init__(self,x = 1,y = 1,z = 1,w = 1):
self.x = x
self.y = y
self.z = z
self.w = w
def foo(self, **kwargs):
[x,y,z,w] = prep(['x','y','z','w'],kwargs,self)
return x + y + z + w
c = example(2,2,2,2)
for i in range(0, 10000000):
c.foo(x = 1,y = 2,z = 3,w = 4)
wrapper1.py
By far less efficient than wrapper2.py.
class example(object):
# I can create a default class or a custom one
def __init__(self,x = 1,y = 1,z = 1,w = 1):
self.x = x
self.y = y
self.z = z
self.w = w
def wrapper(self):
def foo(x = self.x, y = self.y, z = self.z, w = self.w):
return x + y + z + w
return foo
c = example(2,2,2,2)
for i in range(0, 10000000):
c.wrapper()(1,2,3,4)
wrapper2.py
class example(object):
# I can create a default class or a custom one
def __init__(self,x = 1,y = 1,z = 1,w = 1):
self.x = x
self.y = y
self.z = z
self.w = w
def wrapper(self):
def foo(x = self.x, y = self.y, z = self.z, w = self.w):
return x + y + z + w
return foo
c = example(2,2,2,2)
k = c.wrapper()
for i in range(0, 10000000):
k(1,2,3,4)
noo1.py
class example(object):
# I can create a default class or a custom one
def __init__(self,U,x = 1,y = 1,z = 1,w = 1):
self.x = x
self.y = y
self.z = z
self.w = w
def noo(x = self.x, y = self.y, z = self.z, w = self.w):
return x + y + z + w
self.noo = noo
c = example(2,2,2,2)
for i in range(0, 10000000):
c.noo(1,2,3,4)
noo2.py
class example(object):
# I can create a default class or a custom one
def __init__(self,x = 1,y = 1,z = 1,w = 1):
self.x = x
self.y = y
self.z = z
self.w = w
def __call__(self):
def noo(x = self.x, y = self.y, z = self.z, w = self.w):
return x + y + z + w
self.noo = noo
c = example(2,2,2,2)
c()
for i in range(0, 10000000):
c.noo(1,2,3,4)
When testing these codes I included the prep function in all of them, just to be shure they had the same basic structure, and thus the time difference would be from the loops.
Related
I'm trying to create a maze through recursive backtracking but I can't seem to call create_maze() properly. From my main menu I call the maze class like this
maze = Maze.create_maze(NoOfRows, NoOfColumns)
However, I get an argument error from create_maze saying I'm missing an additional "y" or my self.path(0 is missing an additional y
Where am I going wrong?
from numpy.random import random_integers as rand
from Generate import ascii_representation
from constants import *
import numpy as np
WALL_TYPE = np.int8
WALL = 0
EMPTY = 1
RED = 2
BLUE = 3
class Maze:
def __init__(self, Width, Height):
self.Width = Width
self.Height = Height
self.board = np.zeros((Width, Height), dtype=WALL_TYPE)
self.board.fill(EMPTY)
def set_borders(self):
self.board[0, :] = self.board[-1, :] = WALL
self.board[:, 0] = self.board[:, -1] = WALL
def is_wall(self, x, y):
return self.board[x][y] == WALL
def set_wall(self, x, y):
self.board[x][y] = WALL
def remove_wall(self, x, y):
self.board[x][y] = EMPTY
def in_maze(self, x, y):
return 0 <= x < self.Width and 0 <= y < self.Height
def write_to_file(self, filename):
f = open(filename, 'w')
f.write(ascii_representation(self))
f.close()
def set_path(self, x, y):
self.board[y][x] = False
#staticmethod
def load_from_file(filename):
with open(filename, 'r') as f:
content = f.readlines()
# remove whitespace characters like `\n` at the end of each line
content = [x.strip() for x in content]
xss = []
for line in content:
xs = []
for c in line:
if c == ' ':
xs.append(EMPTY)
elif c == 'X':
xs.append(WALL)
else:
raise ValueError('unexpected character found: ' + c)
xss.append(xs)
maze = Maze(len(xss), len(xss[0]))
for xs in xss:
assert len(xs) == maze.Height
for i in range(maze.Width):
for j in range(maze.Height):
if xss[i][j] == EMPTY:
maze.remove_wall(i, j)
else:
maze.set_wall(i, j)
return maze
#staticmethod
def complete_maze(Width, Height):
maze = Maze(Width, Height)
for i in range(Width):
for j in range(Height):
maze.board[i][j] = WALL
return maze
def create_maze(x, y):
Maze.set_path(x, y)
all_directions = [[1, 0], [-1, 0], [0, 1], [0, -1]]
random.shuffle(all_directions)
while len(all_directions) > 0:
direction_to_try = all_directions.pop()
node_x = x + (direction_to_try[0] * 2)
node_y = y + (direction_to_try[1] * 2)
if Maze.is_wall(node_x, node_y):
link_cell_x = x + direction_to_try[0]
link_cell_y = y + direction_to_try[1]
self.set_path(link_cell_x, link_cell_y)
self.create_maze(node_x, node_y)
return
Take a look at the definition for set_path:
def set_path(self, x, y):
This expects three parameters. When you call it with Maze.set_path(x,y), you're only giving it two: x and y. Python expects three and in the order self, then x, then y. Python is interpreting the x you give to be self, then the y to be x and then gives an error that y isn't given. But what is actually missing is self!
To fix this, you need to change this call to self.set_path(x, y) (which is a shortcut for Maze.set_path(self, x, y)). You'll also need to pass self to create_maze as well by changing its definition to def create_maze(self, x, y). And finally, change the way you call create_maze() to something like
maze = Maze(NoOfRows, NoOfCols).create_maze(NoOfRows, NoOfColumns)
As an aside, it seems you never use self.Width or self.Height. You should either remove them from __init__ and just take the x and y passed in create_maze(), or change create_maze() to use self.Width and self.Height instead of taking x and y as parameters.
I am trying to create some custom Python classes for my application. When I try to debug my code I can not pick the instances of my custom classes, I receive the error "Object XXX is not picklable".
I found this page https://docs.python.org/3/library/pickle.html#what-can-be-pickled-and-unpickled but I don't understand how I should implement the methods that make my class picklable.
For example how would you modify the following classes so that I can pick instances of them?
class Point3D:
def __init__ (self, x, y, z):
self.x = x
self.y = y
self.z = z
def move(self, vector):
self.x += vector.x
self.y += vector.y
self.z += vector.z
return
def isValidPoint(self):
isNotValid = False
isNotValid = math.isnan(self.x) or math.isnan(self.y) or math.isnan(self.z)
return not isNotValid
And
class PointCloud3D:
def __init__ (self):
self.points = []
def getNumberOfPoints(self):
return len(self.points)
def addPoint(self, point):
self.points.append(point)
return
def addPointCloud3D(self, additionalPointCloud3D):
for self.point in additionalPointCloud3D:
self.addPoint(point)
def getCloudCenter(self):
numberOfPoints = self.getNumberOfPoints()
centersSumX = 0
centersSumY = 0
centersSumZ = 0
for point in self.points:
centersSumX = centersSumX + point.x
centersSumY = centersSumY + point.y
centersSumZ = centersSumZ + point.z
centerX = centersSumX/numberOfPoints
centerY = centersSumY/numberOfPoints
centerZ = centersSumZ/numberOfPoints
center = Point3D(float(centerX), float(centerY) , float(centerZ))
return center
While here you can find the code that I am trying to debug:
from classDatabase import Point3D, PointCloud3D
testPoint1 = Point3D(1.5, 0.2, 2.3)
testPoint2 = Point3D(3.5, 1.2, 5.3)
testPointCloud3D = PointCloud3D()
testPointCloud3D.addPoint(testPoint1)
testPointCloud3D.addPoint(testPoint2)
Finally a screenshot of the issue:
from threading import *
from random import *
class Ant(Thread):
def __init__(self, x, y):
Thread.__init__(self)
self.x = x
self.y = y
def move(self, x, y):
self.x = x
self.y = y
class Ant_farm():
def __init__(self, x, y):
self.x = x
self. y = y
self.matrix = matrix(x, y)
self.condition = Condition()
def move(self, ant):
with self.condition:
x1, y1 = next_post(ant)
while self.matrix[x1][y1]:
self.condition.wait()
self.matrix[ant.x][ant.y] = False
ant.move(x1, y1)
self.matrix[ant.x][ant.y] = True
self.condition.notify_all()
def next_pos(self, ant):
while True:
choice = {0: (ant.x, ant.y - 1),
1: (ant.x + 1, ant.y),
2: (ant.x, ant.y + 1),
3: (ant.x - 1, ant.y)}
x1, y1 = choice[randrange(0, 4)]
try:
self.matrix[x1][y1]
except IndexError:
pass
else:
return x1, y1
def __str__(self):
res = '\n'
for i in range(self.x):
aux = ''
for j in range(self.y):
aux += str(self.matrix[i][j]) + ' '
aux += '\n'
res += aux
return res
def matrix(x, y):
return [[False for j in range(y)] for i in range(x)]
if __name__ == '__main__':
ant_farm = Ant_farm(7, 7)
for i in range(4):
# t = Ant(target = ant_farm.move)
pass
I want to run move function inside Ant threads. I tried to do:
t = Ant(target = ant_farm.move)
But the interpreter says this:
TypeError: init() got an unexpected keyword argument 'target'
I understand the error, but I don't know how to do what I said.
I have written a class to work with three dimensional vectors as follows
class vector(object):
def __init__(self, x=None, y=None, z=None, angle=None):
if angle == None:
self.x, self.y, self.z = x, y, z
if angle != None:
if angle == "rad":
self.r, self.theta, self.phi = x, y, z
if angle == "deg":
self.r = x
self.theta = y * 2 * pi / 360.
self.phi = z * 2 * pi / 360.
self.x = self.r * sin(self.theta) * cos(self.phi)
self.y = self.r * sin(self.theta) * sin(self.phi)
self.z = self.r * cos(self.theta)
def write(self):
file.write("[" + str(self.x) + ",\t" + str(self.y) + ",\t" + str(self.z) + "]")
def write_sph(self):
file.write("[" + str(self.mag()) + ",\t" + str(self.gettheta()) + ",\t" + str(self.getphi()) + "]")
def getx(self):
return self.x
def gety(self):
return self.y
def getz(self):
return self.z
def setx(self, x):
self.x = x
def sety(self, y):
self.y = y
def setz(self, z):
self.z = z
def square(self):
return self.x*self.x + self.y*self.y + self.z*self.z
def mag(self):
return sqrt(self.square())
def gettheta(self):
return arccos(self.z / self.mag())
def getphi(self):
return arctan2(self.y, self.x) # sign depends on which quadrant the coordinates are in
def __add__(self, vector(other)):
v_sum = vector(other.gettx() + self.gettx(), other.getty() + self.getty(), other.getty() + self.getty())
return v_sum
In the last definition I am attempting to override the operator for addition. The definition works by calling a new vector named other and adding its x,y,z components to the corresponding components of self. When I run the code I'm told the syntax for the definition is invalid. How do I correctly define the vector argument for this overriding definition? Also what difference would changing the definition from def __ add __ to simply def add make? i.e what do the underscores denote?
You shouldn't have vector(other) in your parameter list - just say other. Also, you'll need to fix the typos in the add method:
def __add__(self, other):
v_sum = vector(other.getx() + self.getx(), other.gety() + self.gety(), other.getz() + self.getz())
return v_sum
I wrote an implementation of the De Casteljau algorithm to create a Bezier curve. My problem is the function ignores the second control point, it does calculate some kind of curve, but it is not correct.
def DeCasteljau(CNTRL_P, t):
ReP = points.point()
Ret = points.point()
n = len(CNTRL_P)
k = 0
tmp = 0
while k < n:
tmp = (((1 - t)**((n-1) - k)) * (t**k))
ReP.addP(CNTRL_P[k])
#ReP.Prnt()
ReP.mulP(tmp)
Ret.addP(ReP)
ReP.Clr() #ReP => (0,0)
tmp = 0
k = k + 1
return Ret
For example: CNTRL_P = [P0, P1, P2]
It ignores P1
class point():
def __init__(self, X = 0, Y = 0):
self.x = X
self.y = Y
def addP(self, P1):
self.x = self.x + (P1.getX())
self.y = self.y + (P1.getY())
def subP(self, C = 0, D = 0):
self.x = self.x - C
self.y = self.y - D
def mulP(self, C):
self.x = self.x * C
self.y = self.y * C
def getX(self):
a = self.x
return a
def getY(self):
a = self.y
return a
def Prnt(self):
print "X:", self.x,"Y:", self.y
def Clr(self):
self.x = 0
self.y = 0
Implementation looks faulty. Where's the recursion?
Does this give you better results?
def DeCasteljau2(CNTRL_P, t):
tmp_points = CNTRL_P[:]
while len(tmp_points) > 1:
for k in range(len(tmp_points)-1):
ReP = point()
ReP2 = point()
ReP.addP(tmp_points[k])
ReP2.addP(tmp_points[k+1])
ReP.mulP((1-t))
ReP2.mulP(t)
ReP.addP(ReP2)
tmp_points[k] = ReP
tmp_points.pop()
return tmp_points[0]
This is the result after each iteration:
P0 | P1 | P2
P0 * (1-t) + P1 * t | P1 * (1-t) + P2
(P0 * (1-t) + P1 * t)*(1-t) + (P1 * (1-t) + P2)*t
You repeat the algorithm until you only have 1 point left. Each point P(n) in the next solution is the result of P(n) * (1-t) + p(n+1) * t from the last solution. At each iteration the last point is discarded since there is no next point that you could multiply and add with.
Wikipedia probably can explain that better than me: link