Scipy Throwing a Tyoe Error when used inside a class - python-3.x

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.

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)

Python : can't pass "self" as the only argument

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.

Dyanmic Class Creation in Python: TypeError: __init__() takes 1 positional argument but 2 were given

Trying to take the header form a .csv file and use it to define a class in Python. The goal is to process all subsequent lines in the file as class objects. Using a for loop I’ve translated the header to generate the human readable elements of a class constructor. I’m getting this error:
TypeError: init() takes 1 positional argument but 2 were given
I’ve viewed some posts about this error here on StackOverflow, but trying to better understand the issue in this use case. Here is a what I’m trying to accomplish:
with open ('fooFile.csv','r') as csvInputFile:
filereader = csv.reader(csvInputFile)
header = []
header.append(next(filereader))
def buildSelfStatements (header):
classBuilder = []
for x in trimHeader:
classBuilder.append('self.'+x+'='+x)
return classBuilder
actionableHeader = buildSelfStatements(header)
class fooList:
def __init__(self):
actionableHeader
fooInstance = fooList(next(filereader))
Per the answer below I also tried:
class fooList:
def __init__(self, header):
actionableHeader
fooInstance = fooList(next(filereader))
I get the error on the last line. I realize this may not be possible, but I am open to learning from why this can’t be done if anyone has insights.

TypeError: __init__() takes 4 positional arguments but 5 were given, added all elements still problem on accesing elements

I am trying for multiple inheritance, but upon passing super() on my child class , it showing Type error. How can i solve the issue im new to python
class Employee:
def __init__(self,first,last,salary):
self.first=first
self.last=last
self.salary=salary
self.email="{}{}#company.com".format(first,last)
class administrator:
def __init__(self,age):
self.age=age
class Manager(Employee,administrator):
def __init__(self,first,last,salary,age,gender):
super().__init__(first,last,salary,age)
self.gender=gender
manager1=Manager("Max","Milan",50000,26,"male")
print(manager1.email)
print(manager1.gender)
I was expecting when
print(manager1.email)
print(manager1.gender) to produce following outputs
MaxMilan#company.com
male

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)

Resources