Is it possible to define a function in a Class - python

I have a problem with my python code specialy when I'm trying to define a function in a Class. Indeed, I want to call this function (which is in a file i called BC.py) in my main program which i called PBC.py
Class BC():
self.nmodes
self.L_ch
self.w
def func1(self,x):
self.k_ch=self.nmodes*self.L_ch*self.w
f=x**3+4*x*self.k_ch+15*self.k_ch
return f
In my main programm i did:
from BC import *
A=BC()
C=func1(self,x)
Then I got this error:
The parameters file have been imported succesfully
Traceback (most recent call last):
File "PBC.py", line 35, in <module>
C =func1(A,eps)
NameError: name 'func1' is not defined
Please do you know where i am wrong?
The thing is, when i don't include the function in my class everything works well,
Class BC():
self.nmodes
self.L_ch
self.w
def func1(self,x):
self.k_ch=self.nmodes*self.L_ch*self.w
f=x**3+4*x+15
return f
Exept that when i use only the function, all the parameters I defined before are not recognized???
For example:
r_0=scipy.optimize.fsolve(func1,0.003,args=(0.032))
I got this error:
The parameters file have been imported succesfully
Traceback (most recent call last):
File "PBC.py", line 75, in <module>
R_0=scipy.optimize.fsolve(func1,float(eps_real),args=(eps))
File "/usr/local/lib64/python2.7/site-packages/scipy/optimize/minpack.py", line 127, in fsolve
res = _root_hybr(func, x0, args, jac=fprime, **options)
File "/usr/local/lib64/python2.7/site-packages/scipy/optimize/minpack.py", line 183, in _root_hybr
_check_func('fsolve', 'func', func, x0, args, n, (n,))
File "/usr/local/lib64/python2.7/site-packages/scipy/optimize/minpack.py", line 14, in _check_func
res = atleast_1d(thefunc(*((x0[:numinputs],) + args)))
File "/home/cfd1/ndiaye/ATACAMAC/BCT_dev.py", line 75, in func1
self.k_ch=self.nmodes*self.pi/self.L_ch+eps/self.L_ch
AttributeError: 'numpy.ndarray' object has no attribute 'nmodes'
Someone can help?
Thank you very much.
Thank you for your answer but it isn't working, i still got this error:
Traceback (most recent call last):
File "PBC.py", line 36, in <module>
C =A.func1(x)
Now i'm trying with a very simplified script:
class real :
def __init__(self):
self.nmodes = 4
self.L_ch = 1
self.w = 2
def func1(self,x):
self.k_ch=self.nmodes*self.L_ch*self.w
f=x**3+4*x*self.k_ch+15*self.k_ch
return f
And my main program is:
from dev import *
A=real()
C=A.func1(x)
Unfortunately it seems not working to caus' i have the same traceback error.
Thank you.

You should call it this way:
from BC import *
A=BC()
C=A.func1(x)
Edit for comment:
Please take care of the code format:
class real :
def __init__(self):
self.nmodes = 4
self.L_ch = 1
self.w = 2
def func1(self,x):
self.k_ch=self.nmodes*self.L_ch*self.w
f=x**3+4*x*self.k_ch+15*self.k_ch
return f

Call the function this way (recommended):
A = BC()
C = A.func1(x)
or this other (less used and not recommended, just mentioned as information):
C = BC.func1(A, x)
Note: I would recommend you to rename your file with a name different than the class BC, because it confuses Python. Also, don't forget to declare x.

Related

AttributeError: undefined symbol when using shared library

This is my first question and I might be doing something wrong.
I am trying to implement a Python application with a library already written in C.
I have created the shared library and I am using ctypes to use it in my Python script.
This is a small part of the script.
from ctypes import *
KYBER_SYMBITES = 32
CRYPTO_PUBLICKEYBITES = 800
CRYPTO_SECRETKEYBITES = 1664
def key_generation():
out_lib = CDLL("./PQCgenKAT_kem.so")
out_lib.crypto_kem_keypair.restype = c_int
out_lib.crypto_kem_keypair.argtypes(POINTER(c_char_p),
POINTER(c_char_p))
pk = [] * CRYPTO_PUBLICKEYBITES
sk = [] * CRYPTO_SECRETKEYBITES
ret_val = out_lib.crypto_kem_keypair(pk,sk)
couple = [] * 2
couple.insert(0,pk)
couple.insert(1,sk)
if ret_val != 0 :
print("ERROR")
return couple
But when I try to test a main file that calls this method I get this error
ale#ale-VirtualBox:~/Desktop/TEST$ /bin/python3
/home/ale/Desktop/TEST/main.py
Traceback (most recent call last):
File "/home/ale/Desktop/TEST/main.py", line 4, in <module>
lista = r.key_generation()
File "/home/ale/Desktop/TEST/RING.py", line 12, in key_generation
out.crypto_kem_keypair.argtypes = [(POINTER(c_char_p),
File "/usr/lib/python3.9/ctypes/__init__.py", line 387, in __getattr__
func = self.__getitem__(name)
File "/usr/lib/python3.9/ctypes/__init__.py", line 392, in __getitem__
func = self._FuncPtr((name_or_ordinal, self))
AttributeError: ./PQCgenKAT_kem.so: undefined symbol: crypto_kem_keypair
This is my first approach to shared libraries. Can anyone help me solve this problem and figure out where am I wrong?

TypeError: 'list' object is not callable in Python in mathematical programming

I have a funtion defined in a class
class someClass:
def objFunction(self, weights):
return [self.obj1(weights), self.obj2(weights), self.obj3(weights)]
def asf(self, f):
def obj(x):
return np.max(np.array(f(x[0],x[1],x[2])))+0.00001*np.sum(f(x[0],x[1],x[2]))
res=minimize(obj,
[0.3,0.3,0.4], method='SLSQP'
,jac=ad.gh(obj)[0],options = {'disp':True, 'ftol': 1e-20,
'maxiter': 1000})
return res
where obj1, obj2 and obj3 are some objective functions to optimized. I am running this method making an object separately:
newObj = SomeClass()
newObj.objFunction(weights)
This works fine and give expected results. But when I used the same method inside another method in the class it returns the above mentioned error. This is how I am doing:
a = someClass()
a.asf(a.objFunction(weights)
It throws this:
Traceback (most recent call last):
File "D:/*******.py", line 332, in <module>
print(investment.asf(obj1(w),ref,ideal,nadir, rho))
File "*******.py", line 313, in asf
,options = {'disp':True, 'ftol': 1e-20, 'maxiter': 1000})
File "C:\Users\*****\Downloads\WinPython-64bit-3.5.1.2\python-3.5.1.amd64\lib\site-packages\scipy\optimize\_minimize.py", line 455, in minimize
constraints, callback=callback, **options)
File "C:\Users\*****\Downloads\WinPython-64bit-3.5.1.2\python-3.5.1.amd64\lib\site-packages\scipy\optimize\slsqp.py", line 363, in _minimize_slsqp
fx = func(x)
File "C:\Users\*******\Downloads\WinPython-64bit-3.5.1.2\python-3.5.1.amd64\lib\site-packages\scipy\optimize\optimize.py", line 289, in function_wrapper
return function(*(wrapper_args + args))
File "D:********.py", line 305, in obj
return np.max(np.array(f(x[0], x[1], x[2], x[3])))+rho*np.sum(f(x[0], x[1], x[2], x[3]))
TypeError: 'list' object is not callable
I think I am doing some OOP (object oriented programming) error in coding because I am not good at it. Any suggestions for this ? Thanks
a.objFunction(weights) returns a list, that's clear from the definition.
a.asf expects one argument called f, which in the definition gets used like:
f(x[0],x[1],x[2])
So you are giving a.asf a list and trying to call it like a function.

Python class and function

I defined a function in my class, but when i called this function into my main program:
class real :
def __init__(self):
self.nmodes = 4
self.L_ch = 1
self.w = 2
def func1(self,x):
self.k_ch=self.nmodes*self.L_ch*self.w
f=x**3+4*x*self.k_ch+15*self.k_ch
return f
And my main program is:
from dev import *
A=real()
C=A.func1(x)
Unfortunately i got this error:
Traceback (most recent call last):
File "PBC.py", line 4, in <module>
C=A.func1(0.2)
AttributeError: real instance has no attribute 'func1'
When i don't include the function in my class, my parameters are not recognized and i got this error:
Traceback (most recent call last):
File "PBC.py", line 75, in <module>
R_0=scipy.optimize.fsolve(func1,float(eps_real),args=(eps))
File "/usr/local/lib64/python2.7/site-packages/scipy/optimize/minpack.py", line 127, in fsolve
res = _root_hybr(func, x0, args, jac=fprime, **options)
File "/usr/local/lib64/python2.7/site-packages/scipy/optimize/minpack.py", line 183, in _root_hybr
_check_func('fsolve', 'func', func, x0, args, n, (n,))
File "/usr/local/lib64/python2.7/site-packages/scipy/optimize/minpack.py", line 14, in _check_func
res = atleast_1d(thefunc(*((x0[:numinputs],) + args)))
File "/home/cfd1/ndiaye/ATACAMAC/BCT_dev.py", line 75, in func1
self.k_ch=self.nmodes*self.pi/self.L_ch+eps/self.L_ch
AttributeError: 'numpy.ndarray' object has no attribute 'nmodes'
What can i do to avoid all this? Thank you for your answers.
Your above code runs if you just fix the indentation:
class real :
def __init__(self):
self.nmodes = 4
self.L_ch = 1
self.w = 2
def func1(self,x):
self.k_ch=self.nmodes*self.L_ch*self.w
f=x**3+4*x*self.k_ch+15*self.k_ch
return f
A=real()
C=A.func1(5)
You have an indentation error. The lines starting def func1 should be lined up with def __init__.

error in a python class with an not iterable object

i have a the following error message
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\IPython\core\interactiveshell.py", line 2721, in run_code
exec code_obj in self.user_global_ns, self.user_ns
File "<ipython-input-257-84ae6ec7b6f6>", line 1, in <module>
accuracy.ra_os
File "<ipython-input-255-a91d95432efe>", line 32, in ra_os
return np.average([(ref.intersection(s).area/s.area) for s in seg])
TypeError: 'Polygon' object is not iterable
where Polygon is the Polygon class of shapely.
i have my own class Accuracy: stat values between reference (one) and segmented (one or more) polygons
ref = <shapely.geometry.polygon.Polygon at 0x4997b38>
seg = [<shapely.geometry.polygon.Polygon at 0x4b972e8>, <shapely.geometry.polygon.Polygon at 0x49c7390>]
import math
import numpy as np
from shapely.geometry import Polygon
nan = np.nan
class Accuracy(object):
def __init__(self, ref, seg=None):
self.ref = ref
self.seg = seg
#property
def area(self):
return self.ref.area
#property
def perimeter(self):
return self.ref.length
#property
def centroidX(self):
return self.ref.centroid.x
#property
def centroidY(self):
return self.ref.centroid.y
#property
def segments(self):
if self.seg:
return len(self.seg)
else:
return 0
#property
def ra_or(self):
if self.seg:
return np.average([(ref.intersection(s).area/ref.area) for s in seg])
else:
return nan
#property
def ra_os(self):
if self.seg:
return np.average([(ref.intersection(s).area/s.area) for s in seg])
else:
return nan
accuracy = Accuracy(ref, seg_overlap)
accuracy.ra_os
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\IPython\core\interactiveshell.py", line 2721, in run_code
exec code_obj in self.user_global_ns, self.user_ns
File "<ipython-input-45-84ae6ec7b6f6>", line 1, in <module>
accuracy.ra_os
File "<ipython-input-7-1e04291926b0>", line 35, in ra_os
return np.average([(ref.intersection(s).area/s.area) for s in seg])
TypeError: 'Polygon' object is not iterable
if i run the function outside the class i have not this error
np.average([(ref.intersection(s).area/ref.area) for s in seg_overlap])
Out[47]: 0.48709794373000681
Did you mean to say self.seg instead of just seg:
return np.average([(ref.intersection(s).area/ref.area) for s in self.seg])
^^^^^
(in both functions)
I think you're accidentally referring to the global object with the same name.

Python TypeErrors: "' list' object is not callable" and "'function' object is unsubscriptable"

I have the following code:
from random import randint,choice
add=lambda x:lambda y:x+y
sub=lambda x:lambda y:x-y
mul=lambda x:lambda y:x*y
ops=[[add,'+'],[sub,'-'],[mul,'*']]
def gen_expression(length,left,right):
expr=[]
for i in range(length):
op=choice(ops)
expr.append([op[0](randint(left,right)),op[1]])
return expr
def eval_expression (expr,x):
for i in expr:
x=i[0](x)
return x
def eval_expression2 (expr,x):
for i in expr:
x=i(x)
return x
[snip , see end of post]
def genetic_arithmetic(get,start,length,left,right):
batch=[]
found = False
for i in range(30):
batch.append(gen_expression(length,left,right))
while not found:
batch=sorted(batch,key=lambda y:abs(eval_expression(y,start)-get))
print evald_expression_tostring(batch[0],start)+"\n\n"
#combine
for w in range(len(batch)):
rind=choice(range(length))
batch.append(batch[w][:rind]+choice(batch)[rind:])
#mutate
for w in range(len(batch)):
rind=choice(range(length))
op=choice(ops)
batch.append(batch[w][:rind]+[op[0](randint(left,right)),op[1]]+batch[w][rind+1:])
found=(eval_expression(batch[0],start)==get)
print "\n\n"+evald_expression_tostring(batch[0],start)
When I try to call to call genetic_artihmetic with eval_expression as the sorting key, I get this:
Traceback (most recent call last):
File "<pyshell#113>", line 1, in <module>
genetic_arithmetic(0,10,10,-10,10)
File "/home/benikis/graming/py/genetic_number.py", line 50, in genetic_arithmetic
batch=sorted(batch,key=lambda y:abs(eval_expression(y,start)-get))
File "/home/benikis/graming/py/genetic_number.py", line 50, in <lambda>
batch=sorted(batch,key=lambda y:abs(eval_expression(y,start)-get))
File "/home/benikis/graming/py/genetic_number.py", line 20, in eval_expression
x=i[0](x)
TypeError: 'function' object is unsubscriptable
And when I try the same with eval_expression2 as the sorting,the error is this:
Traceback (most recent call last):
File "<pyshell#114>", line 1, in <module>
genetic_arithmetic(0,10,10,-10,10)
File "/home/benikis/graming/py/genetic_number.py", line 50, in genetic_arithmetic
batch=sorted(batch,key=lambda y:abs(eval_expression2(y,start)-get))
File "/home/benikis/graming/py/genetic_number.py", line 50, in <lambda>
batch=sorted(batch,key=lambda y:abs(eval_expression2(y,start)-get))
File "/home/benikis/graming/py/genetic_number.py", line 25, in eval_expression2
x=i(x)
TypeError: 'list' object is not callable
As far as i can wrap my head around this, my guess is that sorted() is trying to recursively sort the sublists,maybe? What is really going on here?
Python version is 2.6 - the one in the debian stable repos.
[snip] here:
def expression_tostring(expr):
expr_str=len(expr)*'('+'x '
for i in expr :
if i[1]=='*':
n=i[0](1)
else:
n=i[0](0)
expr_str+=i[1]+' '+str(n)+') '
return expr_str
def evald_expression_tostring(expr,x):
exprstr=expression_tostring(expr).replace('x',str(x))
return exprstr+ ' = ' + str(eval_expression(expr,x))
x=i[0](x) #here i is a function so you can't perform indexing operation on it
x=i(x) #here i is a list so you can't call it as a function
in both cases the value of i is fetched from expr, may be expr contains different type of object than what you're assuming here.
Try this modification:
def gen_expression(length,left,right):
expr=[]
for i in range(length):
op=choice(ops)
expr.append([op[0], randint(left,right),op[1]])
return expr
def eval_expression (expr,x):
for i in expr:
x=i[0](i[1])
return x
You had expr.append([op[0](randint(left,right)),op[1]]) which will put the return value of the calling the function into the 0th index.

Categories

Resources