Python : can't pass "self" as the only argument - python-3.x

I'm writing a code to simplify a graph. In this case I've needed to remove a node of degree 2 and connect its two neighbors each other. Here is the simplified code
class node():
def __init__(self,ind):
#some code
self.neighbors=queue() #queue is another class defined by me
self.distances=queue()
#some code
def addngh(self,nd,distance):
#some code
def remngh(self,nd): #remove node "nd" from neighbors queue
#some code
def d2noderem(self): #removing self node from its left,right neighbors' "neighbors" queue by passing self to left and right's "remngh" function
left,right = self.neighbors[0:2]
#some code
left.remngh(self) #======= Error occurs at here ==========
right.remngh(self)
#some code
when I call that d2noderem function the following error occurs
File "/path/to/file/simplifygraphs.py", line 51, in d2noderem left.remngh(self)
TypeError: remngh() missing 1 required positional argument: 'nd'
Then I tried with
left.remngh(self,self)
and this is the result
File "/path/to/file/simplifygraphs.py", line 51, in d2noderem left.remngh(self,self)
TypeError: remngh() takes 2 positional arguments but 3 were given
I can't understand how did the no of args increased from 0 to 3 by adding 1 more argument.
And I couldn't find a solution for this problem yet.
How to overcome this type of problem?
I appreciate your help very much

The method 'remng' expects an argument as defined by the parameter 'nd' in def remngh(self,nd): Since you're calling it without supplying the expected argument, it's throwing an error.
You should either provide the expected argument or rewrite the function entirely.

Related

TypeError: show() takes 1 positional argument but 2 were given

The simple code below is giving the error in the title. The compiler is complaining that 2 positional arguments were given to plt.show(), but only one was expected. However as you can see from the code only one argument "fig1" was given?
def test_plot_episode_stats(stats):
fig1 = plt.figure(figsize=(10, 5))
plt.plot(stats.episode_lengths)
plt.show(fig1)
return fig1
EpisodeStats = namedtuple("Stats", ["episode_lengths", "episode_rewards"])
if name == 'main':
stats = EpisodeStats(
episode_lengths=np.random.randint(10, size=10),
episode_rewards=np.random.randint(10, size=10))
test_plot_episode_stats(stats)
The function plt.show() means to show all open figure windows.
So, it does not necessarily need to accept any fig object as positional argument.
Actually, it only supports the keyword argument block=Ture|False, according to the document.
In addition, the function signature plt.show(*args, **kwargs) does not mean it accept fig object as positional argument.
The true signature depends on the backend currently in use, as the code inside plt.show():
def show(*args, **kwargs):
'''...'''
return _backend_mod.show(*args, **kwargs)

Scipy Throwing a Tyoe Error when used inside a class

I have this three functions inside a class below
def metrics(self,*args):
portfolio_return=np.sum(self.returns.mean()*self.weights)*252
portfolio_volatility=np.sqrt(np.dot(self.weights.T,np.dot(self.returns.cov()*252,self.weights)))
return np.array([portfolio_return,portfolio_volatility,portfolio_return/portfolio_volatility])
def objective(self):
return -self.metrics()[2]
def optimize(self):
optimum=optimization.minimize(fun=self.objective,x0=self.weights,args=self.returns,method='SLSQP',
bounds=self.bounds,constraints=self.constraints)
self.optimum = optimum
return self.optimum
This throws a
TypeError: objective() takes 1 positional argument but 3 were given
I tried adding *args as argument to objective. The code runs, but unfortunately it wasn't able to get the best parameters.

Python 3 Overriding method with different signature in the derived class

i want to override a method from a base class in the derived class.
I don't have access to the code of the base class, so i must inherit from it and have to override the method.
The overriding method needs to call a function with any number of arguments, passed as argument therefore i have to change the methods signature.
But i get the following error when i try to run the following code:
TypeError: 'str' object is not callable
Example code:
# I don't have access to this code:
# _____________________________
class Base:
def run(self):
pass
# _____________________________
# Only to the following:
class Sub(Base):
def run(self, func, *args):
func(*args)
def call_me(test1, test2):
print(test1+test2)
test = Sub
test.run(call_me, "test1 ", "test2")
Any suggestions how i can solve this problem?
I want the method "run" to be able to call any function with unkown numbers of arguments
--------- EDIT ---------
Ok sorry, i found the solution:
It was just a terrible typo - my bad!
The typo was missing braces in the following statement:
test = Sub
must be:
test = Sub()

Python: ' __init__() takes 7 positional arguments but 8 were given' -- but both statements seem wrong

I have a class that is called in a couple of contexts:
class Datamodel:
def __init__(self, habvalues, hablist=[], orglist=[], genlist=[]):
self.habvalues = habvalues
self.uses_database = False
if hablist and orglist and genlist:
self.hablist = hablist
self.orglist = orglist
self.genlist = genlist
self.uses_database = True
There is one method that calls this class using only the habvalues parameter, and it seems to work fine. However, when called using all the parameters, with lists that are shown by my logging calls to contain valid data, I get the following error message:
__ init__() takes 7 positional arguments but 8 were given
The calling function reads like this:
self.newmodel = evocontrol.Datamodel(self.habvalues, self.habRecords, self.orgRecords, self.genlist)
So, the error message seems to be wrong. There are not 7 positional arguments in my code, only 4. And only 4 are given.
What could be the source of a miscount such as this? What kinds of things should I be looking for here?
Please, try passing the arguments as keyword arguments
self.newmodel = evocontrol.Datamodel(self.habvalues, hablist=self.habRecords, orglist=self.orgRecords, genlist=self.genlist)

Celery handling named argument

I have a celery task like this
#app.task(bind=True,max_retries=3, default_retry_delay=1 * 60)
def doTargetprefilter(self,*args,**kwargs ):
I am calling this as
args = [None,sourcedns, targetdnlist]
kwargs= {'workername':workername,}
result = r.doTargetprefilter.apply_async(*args,**kwargs)
However I am getting a strange error
File "/usr/local/lib/python3.4/dist-packages/celery/app/amqp.py", line 254, in publish_task
raise ValueError('task kwargs must be a dictionary')
ValueError: task kwargs must be a dictionary
A small unit test of the invocation works fine;
def test_doTargetprefilter(self):
from ltecpxx.mrosimpleexecutor import doTargetprefilter
s=[1,2,3]
t=[1,2,2]
workername="ltecpxx.mrosimpleexecutor.SimplePrefilter"
args =[None,s,t]
kwargs={'wokername':workername}
doTargetprefilter(*args,**kwargs)
I have tried all sorts of combinaiton and also seen the apply_async documentation. It works if I make it as a normal method (without *args and **kwargs); What am I doing wrong
The bind annotation supplies the self; So we need to remove that from the args list, and all the arguments must be in a tuple when we call apply_async. Changing these two will give
args = [sourcedns, targetdnlist]
kwargs= {'workername':workername}
result = r.doTargetprefilter.apply_async((args),kwargs)
And function signature
#app.task(bind=True,max_retries=3, default_retry_delay=1 * 60) # retry in 1 minutes.
def doTargetprefilter(self,*args,workername=""):

Resources