Cant match a function with an array in same class(no attribute) - python

import random
import numpy as np
np.set_printoptions(suppress=True)
gladList = np.empty((128,5))
class Gladiators:
def __init__(self,name1,hp,atd,armor,accuracy):
self.name1=name1
self.hp=hp
self.atd=atd
self.armor=armor
self.accuracy=accuracy
#staticmethod
def createRobot(x):
for i in range(x):
gladList[i]=(i,random.randint(1000,1500),random.randint(40,80),random.randint(0,100),random.randint(60,100))
print(gladList[i])
def info(self):
print("Analyzing Gladiator...")
print("Name:",self.name1,"Health:",self.hp,"AD:",self.atd,"Armor:",self.armor,"Accuracy:",self.accuracy)
def isAlive(self):
pass
def fight(self):
pass
Gladiators.createRobot(128) g1=gladList[41] ig1=Gladiators.info(g1) print(ig1)
> Error: line 27, in info
print("Name:",self.name1,"Health:",self.hp,"AD:",self.atd,"Armor:",self.armor,"Accuracy:",self.accuracy)
AttributeError: 'numpy.ndarray' object has no attribute 'name1'
>
I guess i should use self instead of using static method but im still getting error anyways

Your usage of the info method is wrong. It's not a static method, so you can't call it on the class.
You have two options:
Call info properly
gladiator = Gladiators.createRobot(128)
print(gladiator.info())
Redefine info as a static method that takes a gladiator as an argument (Warning: I don't necessarily think this is a good idea).
...
#staticmethod
def info(some_gladiator):
print("Analyzing Gladiator...")
print(
"Name:", some_gladiator.name1,
"Health:", some_gladiator.hp,
"AD:", some_gladiator.atd,
"Armor:", some_gladiator.armor,
"Accuracy:", some_gladiator.accuracy
)
...
gladiator = Gladiators.createRobot(128)
print(Gladiators.info(gladiator))

Related

error on getting dataframe defined in other object i.e. TypeError: 'DataFrame' object is not callable

i am new to python and trying to create some code for my understanding. i am getting error for getting tick_data in another object.
following is my code where i defined dataframe
class MarketDataLoader():
def __init__(self,symbols,cashPerTrade,broker_config: 'BrokerConfig'):
self._tick_data = None
#few other init var
#property
def tick_data(self) -> 'pandas.DataFrame':
return self._tick_data
def process_tick_data(self, data, dataframe):
# some processing for tick data and assign value to tick data
def process_and_resample_tick_data(self):
self._api.subscribe_market_data(self._symbols, (self.process_tick_data,))
when process_and_resample_tick_data method got called it starts streaming to process_tick_data method
then in trade executor class
class TradeExecutor():
def __init__(self,market_data: 'MarketDataLoader',trade_config:'TradeConfig',broker_config:'BrokerConfig'):
print("Init Trade execute")
self._market_data = market_data
self._trade_config = trade_config
self._broker_config =broker_config
def start_trade(self):
logger.info("starting trade from Trade Executor for ",self._trade_config.symbols,
" cash for trade ",self._trade_config.cash_per_trade)
while True: # repeat until we get all historical bars
time.sleep(10)
print("trade time ",self._market_data)
#error on following line of code
tick_frame = self._market_data.tick_data()
i am getting error on tick_frame = self._market_data.tick_data() i am not sure how to resolve following error
tick_frame = self._market_data.tick_data()
TypeError: 'DataFrame' object is not callable
python-BaseException
You're trying to call a method declared as a property.
When we use the #property decorator we treat the method as an attribute. For example, suppose we have the following class:
class JBug(object):
def __init__(self):
name = 'Junie'
#property
def hello(self):
return "Hello, my name is %s" % name
To get the desired behavior we do not call hello, but treat it as an attribute:
>>> J = JBug()
>>> print(J.hello)
Hello, my name is Junie

Python How to call a method from inside another method

I am a new OOP. I have written the following classes and methods and want to call a method from inside another method. However, I get an error saying name polynomial (method) is not defined. Any ideas why?
#Imports
import numpy as np
from scipy.signal import argrelextrema
from scipy import optimize
class MaxImpact():
def __init__(self,X,Y):
self.X = X
self.Y = Y
self.minima_index = argrelextrema(self.Y,np.less)
self.maxima_index = argrelextrema(self.Y,np.greater)
self.approx_converge_pt = []
self.approx_converge_idx = []
# .... (bunch of other methods)
def calc_convergePt_X(self):
for i in range(1,len(self.Y)):
if (self.Y[i-1] < 0 and self.Y[i] > 0) or (self.Y[i-1] > 0 and self.Y[i] < 0):
self.approx_converge_idx.append(i-1)
for i in self.approx_converge_idx:
self.x_val = self.X[i]
return(self.x_val)
def polynomial(self):
func = clf4.intercept_[0] + clf4.coef_[0][1] * self.X + clf4.coef_[0][2]*np.power(self.X,2) + clf4.coef_[0][3]*np.power(self.X,3) + clf4.coef_[0][4]*np.power(self.X,4)
def neutral_state(self):
sol = optimize.root(polynomial(),self.x_val)
maxImp2 = MaxImpact(XX,YY4)
print(maxImp2.calc_convergePt_X())
print(maxImp2.neutral_state())
Here I want to call the polynomial method which contains the polynomial eq within the neutral state method. I end up with the error "name polynomial is not defined"
Methods must be called on an instance. To call a method on the same instance, use self to refer to it:
def neutral_state(self):
sol = optimize.root(self.polynomial(), self.x_val)
please use self keyword while calling the class member.
sol = optimize.root(self.polynomial(),self.x_val)
Python is raising a NameError because as far as it's concerned, polynomial doesn't exist. You've defined it as a method of the MaxImpact class, and therefore the function will only be called when you call self.polynomial(), telling python that it is part of the MaxImpact class.
To call a method when using OOP in Python, and in this case, you can simply use self.methodname()
In your case:
class return_hello():
def polynomial(self):
return print("hello")
def neutral_state(self):
self.polynomial()

Wrapping my HashTable class

I need to be able to wrap a HashTable class. After reading about wrappers I am pretty sure this is a bad usage of a wrapper, however it is in my assignment. ( I have different data structures that need to be easily swapped in a program)
I have the following code:
from HashTable import HashTable
class HashTableWrapper(HashTable):
def __init__(self, probe, size):
super().__init__(probe, size)
def tableInsert(self, searchKey, newItem):
return self.HashTable.tableInsert(searchKey, newItem)
def tableRetrieve(self, searchKey):
return self.HashTable.tableRetrieve(searchKey)
def tableDelete(self, searchKey):
return self.HashTable.tableDelete(searchKey)
When I use:
x = HashTableWrapper("linearProbe", 100)
Everything is fine however, if I would use the following:
x.tableInsert(4, 6)
I get the following error: AttributeError: 'HashTableWrapper' object has no attribute 'HashTable'
I think something is wrong with the return part since python also highlights all the HashTable parts.
Some help would be appreciated.
Edit: I got the following example:
class BSTTableWrapper:
def tableInsert(item):
return self.bst.searchtreeInsert(item)
self.HashTable is never initialized so calling self.HashTable.<function or variable> would never work. If the HashTable object has the method tableInsert, then all you have to do is
def tableInsert(self, searchKey, newItem):
return self.tableInsert(searchKey, newItem)
def tableRetrieve(self, searchKey):
return self.tableRetrieve(searchKey)
def tableDelete(self, searchKey):
return self.tableDelete(searchKey)
because the functions/methods are inherited from the HashTable.

How can I tell what function called my function? [duplicate]

Python: How to get the caller's method name in the called method?
Assume I have 2 methods:
def method1(self):
...
a = A.method2()
def method2(self):
...
If I don't want to do any change for method1, how to get the name of the caller (in this example, the name is method1) in method2?
inspect.getframeinfo and other related functions in inspect can help:
>>> import inspect
>>> def f1(): f2()
...
>>> def f2():
... curframe = inspect.currentframe()
... calframe = inspect.getouterframes(curframe, 2)
... print('caller name:', calframe[1][3])
...
>>> f1()
caller name: f1
this introspection is intended to help debugging and development; it's not advisable to rely on it for production-functionality purposes.
Shorter version:
import inspect
def f1(): f2()
def f2():
print 'caller name:', inspect.stack()[1][3]
f1()
(with thanks to #Alex, and Stefaan Lippen)
This seems to work just fine:
import sys
print sys._getframe().f_back.f_code.co_name
I would use inspect.currentframe().f_back.f_code.co_name. Its use hasn't been covered in any of the prior answers which are mainly of one of three types:
Some prior answers use inspect.stack but it's known to be too slow.
Some prior answers use sys._getframe which is an internal private function given its leading underscore, and so its use is implicitly discouraged.
One prior answer uses inspect.getouterframes(inspect.currentframe(), 2)[1][3] but it's entirely unclear what [1][3] is accessing.
import inspect
from types import FrameType
from typing import cast
def demo_the_caller_name() -> str:
"""Return the calling function's name."""
# Ref: https://stackoverflow.com/a/57712700/
return cast(FrameType, cast(FrameType, inspect.currentframe()).f_back).f_code.co_name
if __name__ == '__main__':
def _test_caller_name() -> None:
assert demo_the_caller_name() == '_test_caller_name'
_test_caller_name()
Note that cast(FrameType, frame) is used to satisfy mypy.
Acknowlegement: comment by 1313e for an answer.
I've come up with a slightly longer version that tries to build a full method name including module and class.
https://gist.github.com/2151727 (rev 9cccbf)
# Public Domain, i.e. feel free to copy/paste
# Considered a hack in Python 2
import inspect
def caller_name(skip=2):
"""Get a name of a caller in the format module.class.method
`skip` specifies how many levels of stack to skip while getting caller
name. skip=1 means "who calls me", skip=2 "who calls my caller" etc.
An empty string is returned if skipped levels exceed stack height
"""
stack = inspect.stack()
start = 0 + skip
if len(stack) < start + 1:
return ''
parentframe = stack[start][0]
name = []
module = inspect.getmodule(parentframe)
# `modname` can be None when frame is executed directly in console
# TODO(techtonik): consider using __main__
if module:
name.append(module.__name__)
# detect classname
if 'self' in parentframe.f_locals:
# I don't know any way to detect call from the object method
# XXX: there seems to be no way to detect static method call - it will
# be just a function call
name.append(parentframe.f_locals['self'].__class__.__name__)
codename = parentframe.f_code.co_name
if codename != '<module>': # top level usually
name.append( codename ) # function or a method
## Avoid circular refs and frame leaks
# https://docs.python.org/2.7/library/inspect.html#the-interpreter-stack
del parentframe, stack
return ".".join(name)
Bit of an amalgamation of the stuff above. But here's my crack at it.
def print_caller_name(stack_size=3):
def wrapper(fn):
def inner(*args, **kwargs):
import inspect
stack = inspect.stack()
modules = [(index, inspect.getmodule(stack[index][0]))
for index in reversed(range(1, stack_size))]
module_name_lengths = [len(module.__name__)
for _, module in modules]
s = '{index:>5} : {module:^%i} : {name}' % (max(module_name_lengths) + 4)
callers = ['',
s.format(index='level', module='module', name='name'),
'-' * 50]
for index, module in modules:
callers.append(s.format(index=index,
module=module.__name__,
name=stack[index][3]))
callers.append(s.format(index=0,
module=fn.__module__,
name=fn.__name__))
callers.append('')
print('\n'.join(callers))
fn(*args, **kwargs)
return inner
return wrapper
Use:
#print_caller_name(4)
def foo():
return 'foobar'
def bar():
return foo()
def baz():
return bar()
def fizz():
return baz()
fizz()
output is
level : module : name
--------------------------------------------------
3 : None : fizz
2 : None : baz
1 : None : bar
0 : __main__ : foo
You can use decorators, and do not have to use stacktrace
If you want to decorate a method inside a class
import functools
# outside ur class
def printOuterFunctionName(func):
#functools.wraps(func)
def wrapper(self):
print(f'Function Name is: {func.__name__}')
func(self)
return wrapper
class A:
#printOuterFunctionName
def foo():
pass
you may remove functools, self if it is procedural
An alternative to sys._getframe() is used by Python's Logging library to find caller information. Here's the idea:
raise an Exception
immediately catch it in an Except clause
use sys.exc_info to get Traceback frame (tb_frame).
from tb_frame get last caller's frame using f_back.
from last caller's frame get the code object that was being executed in that frame.
In our sample code it would be method1 (not method2) being executed.
From code object obtained, get the object's name -- this is caller method's name in our sample.
Here's the sample code to solve example in the question:
def method1():
method2()
def method2():
try:
raise Exception
except Exception:
frame = sys.exc_info()[2].tb_frame.f_back
print("method2 invoked by: ", frame.f_code.co_name)
# Invoking method1
method1()
Output:
method2 invoked by: method1
Frame has all sorts of details, including line number, file name, argument counts, argument type and so on. The solution works across classes and modules too.
Code:
#!/usr/bin/env python
import inspect
called=lambda: inspect.stack()[1][3]
def caller1():
print "inside: ",called()
def caller2():
print "inside: ",called()
if __name__=='__main__':
caller1()
caller2()
Output:
shahid#shahid-VirtualBox:~/Documents$ python test_func.py
inside: caller1
inside: caller2
shahid#shahid-VirtualBox:~/Documents$
I found a way if you're going across classes and want the class the method belongs to AND the method. It takes a bit of extraction work but it makes its point. This works in Python 2.7.13.
import inspect, os
class ClassOne:
def method1(self):
classtwoObj.method2()
class ClassTwo:
def method2(self):
curframe = inspect.currentframe()
calframe = inspect.getouterframes(curframe, 4)
print '\nI was called from', calframe[1][3], \
'in', calframe[1][4][0][6: -2]
# create objects to access class methods
classoneObj = ClassOne()
classtwoObj = ClassTwo()
# start the program
os.system('cls')
classoneObj.method1()
Hey mate I once made 3 methods without plugins for my app and maybe that can help you, It worked for me so maybe gonna work for you too.
def method_1(a=""):
if a == "method_2":
print("method_2")
if a == "method_3":
print("method_3")
def method_2():
method_1("method_2")
def method_3():
method_1("method_3")
method_2()

Constructor that takes in a method

In Python, can a constructor take in a method of another class as an argument?
I've heard that you can do something like this, but this example isn't working (currently, I'm getting a 'module' object is not callable error):
class GeneticAlgorithm ():
def __init__(self, population, fitness, breed, retain = .3, weak_retain = .15 ) :
self.fitness = fitness
Here fitness is a function defined elsewhere and note that I am importing the class where the function is defined.
edit: Here's the code that actually produces the error
class Solver( ):
def __init__( self, fitness, breed, iterations ):
self.T = Problem()
self.fitness = fitness
self.breed = breed
self.iterations = iterations
def solve( self ):
P = self.T.population(500)
GA = GeneticAlgorithm(P, self.fitness, self.breed) # problem here
Traceback (most recent call last):
File "C:\Users\danisg\Desktop\Other\Problem.py", line 128, in <module>
main()
File "C:\Users\danisg\Desktop\Other\Problem.py", line 124, in main
t = S.solve()
File "C:\Users\danisg\Desktop\Other\Problem.py", line 74, in solve
GA = GeneticAlgorithm(P, self.fitness, self.breed)
TypeError: 'module' object is not callable
And where the Solver is created
def main():
S = Solver(fitness, breed, 35)
print(S.solve())
if __name__ == '__main__':
main()
From the comments, the root of the issue:
I do `import GeneticAlgorithm'. I should not do this? – gjdanis
No, that's not actually correct. What you've done is import the module, not the class that's inside the module. You have two options here - do one or the other:
Change the import to
from GeneticAlgorithm import GeneticAlgorithm
Change the Solver class to use
GA = GeneticAlgorithm.GeneticAlgorithm(P, self.fitness, self.breed)
I'd suggest renaming the module from GeneticAlgorithm.py to something that isn't quite as confusing (genetic_algorithm.py is a good candidate), then using the first option to import just the class from that module - from genetic_algorithm import GeneticAlgorithm
Yes, you could have something like this:
def eats_a_method(the_method):
pass
def another_method():
pass
eats_a_method(another_method)
Take a look at the stack trace:
GA = GeneticAlgorithm(P, self.fitness, self.breed)
TypeError: 'module' object is not callable
It says GeneticAlgorithm is a module, not a function.

Categories

Resources