Type Error Python - python-2.7

I am currently working on a game and I tried to make an image move and I keep getting this error right here
TypeError: unbound method put_here() must be called with create_entity instance as first argument (got int instance instead)
Here is the code for the PlayerEntity.py file the I made.
class create_entity:
def __init__(self, image, name, armor, skills, weapons):
self.entity_image = image
self.entity_name = name
self.entity_armor = armor
self.entity_skills = skills
self.entity_weapons = weapons
def put_here(self,x,y):
screen.blit(self.entity_image, (x,y))
Now here is the main Game file that I was testing this in
if __name__ == '__main__':
import PlayerEntity as p_entity
p_entity.create_entity('test_img.png', 'Default', [], [], [])
p_entity.create_entity.put_here(300,300)

You should save the instantiated object into a variable and use it to call its function:
entity = p_entity.create_entity('test_img.png', 'Default', [], [], [])
entity.put_here(300,300)
This code assumes that import PlayerEntity as p_entity returns a module p_entity that contains the class create_entity (bad name for a class - by the way)

Related

how to pass arguments between pythons scripts in MAYA?

I'm new in python and i'm trying to pass arguments between different scripts but they only update one way:
i'm calling the first script in maya with a shelf like this:
try:
myPM.close()
except:pass
import sys
sys.path.append("C:/Users/manue/Desktop/test")
import UiMayaTest as SBIRP
reload(SBIRP)
myPM = SBIRP.createUI()
this called script 'UiMayaTest.py' is a simple window with an intField entry and a button:
import sys
import maya.cmds as cmds
from functools import partial
def buttonPressed(episode, *args):
passValue(episode, *args)
print '============== buttonPressed ================'
print 'EpisodeName ', EpisodeName
Var = ''
import UiMayaTestFunction
Var = UiMayaTestFunction.FindVarFunc(EpisodeName,Var)
print 'Var : ',Var
def createUI():
myWindow = "SomeWindow"
if cmds.window(myWindow,ex=True):
cmds.deleteUI(myWindow)
cmds.window(myWindow)
cmds.columnLayout( adjustableColumn=True )
cmds.text( label='Episode: ', align='left' )
episode = cmds.intField( "Episode", minValue = 100, maxValue = 1000, value =100)
cmds.button(l="Open Last LIT scene", w=150, h=30, command=partial(buttonPressed,episode))
cmds.setParent("..")
cmds.showWindow()
def passValue(episode, *args):
global EpisodeName
EpisodeName = `cmds.intField( episode, query = True, value = True)`
and the script called by it is called 'UiMayaTestFunction.py' and just return a variable called Var:
def FindVarFunc(EpisodeName, Var):
print '============== FindVarFunc ================'
print 'EpisodeName:' , EpisodeName
Var = 'Hello world'
print 'Var: ',Var
return Var
the variable 'EpisodeName' from UiMayaTest to UiMayaTestFunction is well updated each time i press the button,
but if i change the variable 'Var' in UiMayaTestFunction , it doesn't update it, i've got always the same print or 'Var'...
Thanks by advance for any help...
Well.... it seems that the script does exactly do what it is supposed to do. What result for your Var variable do you expect?
Let's see.. if the button is pressed, the buttonPressed() function is called. There the variable 'Var' is initialized with an empty string ''. Then teh FindVarFunc() is called with the argument Var, what is still an empty string. In the FindVarFunc() the Variable 'Var' is printed and returnde, what is still.... well you guess it: an empty string. And finally the result of the function is assigned to the variable 'Var', and the result is... an empty string which is printed. It could help to assign 'Var' something else but an empty string to see if it works better.

Testing a function with a #cache.memoize gives PicklingError

I have some tests for functions that use cache, for example:
Function:
#retry(stop=stop_after_attempt(3))
#cache.cached(timeout=60, key_prefix='resouce_group_list')
def get_azure_resource_groups():
data = []
resource_client = get_azure_resource_client()
for item in resource_client.resource_groups.list():
data.append(item)
return data
Test:
#patch("dev_maintenance.machines.get_azure_resource_client")
def test_get_azure_list_rg(get_azure_resource_client):
cache.clear()
data = []
with app.app_context():
ret = get_azure_resource_groups()
get_azure_resource_client.assert_called_once()
expected = get_azure_resource_client.return_value.resource_groups.list.return_value
assert len(get_azure_resource_client.return_value.method_calls) == 1
for item in expected:
data.append(item)
assert ret == data
cache.clear()
The above test works fine, it passes, no errors and the test is using cache.
But i got other tests, and the decorator here does not matter, it will give the same error if i change the decorator to #cache.cache:
Function:
#retry(stop=stop_after_attempt(3))
#cache.memoize(60)
def get_azure_machine_info(rg_name, machine_name, expand="instanceView"):
try:
compute_client = get_azure_compute_client()
return compute_client.virtual_machines.get(rg_name, machine_name, expand=expand)
except CloudError:
return None
Test:
#patch("dev_maintenance.machines.get_azure_compute_client")
def test_get_azure_machine_info (get_azure_compute_client):
cache.delete_memoized(get_azure_machine_info)
with app.app_context():
ret = get_azure_machine_info("rg1", "m1")
print(ret)
get_azure_compute_client.assert_called_once()
assert len(get_azure_compute_client.return_value.method_calls) == 1
assert (
ret == get_azure_compute_client.return_value.virtual_machines.get.return_value
)
get_azure_compute_client.return_value.virtual_machines.get.assert_called_once_with(
"rg1", "m1", expand="instanceView"
)
cache.delete_memoized(get_azure_machine_info)
Now here the test fails with the error on this line ret = get_azure_machine_info("rg1", "m1"):
value = None, from_value = PicklingError("Can't pickle <class 'unittest.mock.MagicMock'>: it's not the same object as unittest.mock.MagicMock")
> ???
E tenacity.RetryError: RetryError[<Future at 0x105c7c3d0 state=finished raised PicklingError>]
<string>:3: RetryError
I tried to mock the cache passing a patch decorator like:
#patch("dev_maintenance.machines.cache") or #patch("dev_maintenance.cache")
I tried to set the CACHE_TYPE to null in the test case, instantiating the cache object and passing the config:
cache = Cache()
cache.init_app(app, config={"CACHE_TYPE": "redis"})
but no success so far, any help?
This is a reference to an old answer, but I think that generally MagicMock objects aren't meant to be pickled: https://github.com/thadeusb/flask-cache/issues/52
That error message is different though, and this is more similar to what you are seeing:
Is there a way to make python pickle ignore "it's not the same object " errors
Maybe you could replace the domain prefix to the class like the answer above, but I am not sure it will overcome the other difficulties of pickling a MagicMock class:
`#patch("__main__.get_azure_compute_client")`
I'am writing the answer here for people that need to test functions that are cached with flask-caching and have the same error then me.
What i needed was to create an Object inside the test and make the mock_value = Object like this:
First i create a simple class:
class MachineInfo(object):
pass
Then in my test:
#patch("dev_maintenance.machines.get_azure_compute_client")
def test_get_azure_machine_info (get_azure_compute_client):
cache.clear()
expected_res = MachineInfo()
expected_res.id = "id"
expected_res.name = "machine1"
expected_res.location = "location"
expected_res.hardware_profile = "hardware"
expected_res.storage_profile = "storage"
expected_res.network_profile = "network_profile"
get_azure_compute_client.return_value.virtual_machines.get.return_value = expected_res
res = get_azure_machine_info("rg1", "m1")
assert res == expected_res
cache.clear()
Then i could assert function_call() == Object or function_call() == mock.return_value
This simulates what the actual azure returns, an object, so i just make the mock return the object that i created so i can simulate the function itself.

Write my own keras layer

I want to write my own keras layer with taking as input a tensor with shape (nb_batch, input_dim) and producing a tensor with shape (nb_batch, context_size, output_dim) . I have write a demo below:
class MyLayer(Layer):
def __init__(self, output_dim, context_size, init="uniform", **kwargs):
self.output_dim = output_dim
self.context_size = context_size
self.init = initializations.get(init)
super(MyLayer, self).__init__(**kwargs)
def build(self, input_shape):
input_dim = input_shape[1]
self.W_vec = self.init(
(self.context_size, input_dim, self.output_dim),
name="W_vec")
self.trainable_weights = [self.W_vec]
super(MyLayer, self).build() # be sure you call this somewhere!
def call(self, x, mask=None):
return K.dot(x, self.W_vec)
# return K.dot(x, self.W)
def get_output_shape_for(self, input_shape):
return (input_shape[0], self.context_size, self.output_dim)
when I ran it , got a error "TypeError: build() takes exactly 2 arguments (1 given)"enter code here
Looks like build needs input shape argument
super(MyLayer, self).build(input_shape) # be sure you call this somewhere!

How to invoke a method from combo box event

I am trying to invoke a method from combo box selected change event
with lambda expression but I am stuck with following error
TypeError: () takes no arguments (1 given)
I think I have passed 1 argument as per the method definition, could somebody please help me where I am wrong
or any other combobox selected change event code will be great help!
please note my code
self.boxWidget[boxName].bind("<<ComboboxSelected>>", lambda:invoke_Setting_Group(self))
def invoke_My_method1(self):
print "expand another window"
I am trying to pass the first class object to the second python script file for variable value assigning easeness.I tried to use this combox event change code without lambda then I noticed that this method is getting called automatically so I used lambda to prevent this automatic method calling
Sorry I am not having the knowledge on lambda expression usage; here I used only to prevent the automatic method execution. Without lambda expression I noticed my combo box function starts automatically, I did not understand why it happens so?
I am using TKinter python 2.6
More Detailed Code of above:
#Main_GUI_Class.py
##----------------------
import sys
class App():
def __init__ (self,master,geometry=None,root=None):
try:
self.master=master
if not root:
self.root=Tkinter.Toplevel(master)
def initUI(self):
try:
self.master.title("GUI")
menubar = Menu(self.master)
self.root.config(menu=menubar)
fileMenu.add_command(label='Open')
submenu_ncss.add_command(label='Model Setting',command=lambda:Combo_Expand_Script.Call_Model_Setting(self))
##----------------------
def main():
r = Tkinter.Tk()
r.withdraw()
r.title("GUI Sample")
r.wm_iconbitmap(Pic1)
v = App(r)
r.mainloop()
if __name__ == "__main__":
main()
##Combo_Expand_Script.py
##-----------------------
import sys
import Tkinter
import Main_GUI_Class
def Call_Model_Setting(self):
try:
self.PopUpWin = Toplevel(bg='#54596d',height=500, width=365)
self.PopUpWin.title("POP UP SETTING")
#Combo Boxs in Pop Up
boxNameGroup="boxSetting"
boxPlaceY=0
for Y in range(4):
boxName=boxNameGroup+str(Y)
if Y == 0:
boxPlaceY=50
else:
boxPlaceY=boxPlaceY+40
self.box_value = StringVar()
self.boxWidget[boxName] = ttk.Combobox(self.PopUpWin, height=1, width=20)
if Y== 0:
self.boxWidget[boxName]['values'] = ('A', 'B')
self.boxWidget[boxName].current(1)
if Y== 1:
self.boxWidget[boxName]['values'] = ('X', 'Y')
self.boxWidget[boxName].bind("<<ComboboxSelected>>",lambda:invoke_Setting_Group(self))
self.boxWidget[boxName].place(x=180, y = boxPlaceY)
#Buttons in Pop Up
self.btnApply = tk.Button(self.PopUpWin,width=10, height=1,text="Apply",relief=FLAT,bg=btn_Bg_Color,command=lambda: treeDataTransfer(self,0))
self.btnApply.pack()
self.btnApply.place(x=75, y = 460)
self.btnCancel = tk.Button(self.PopUpWin,width=10, height=1,text="Cancel",relief=FLAT,command=lambda: deleteTreeNodes(self))
self.btnCancel.pack()
self.btnCancel.place(x=170, y = 460)
except IOError:
print "Error: data error"
def invoke_Setting_Group(self):#, event=None
try:
#self.boxName.current(0)
self.boxWidget["boxSetting3"].current(0)
self.PopUpWin['width']=1050
self.PopUpWin['height']=700
self.btnApply.place(x=500, y = 550)
self.btnCancel.place(x=600, y = 550)
self.txtWidget={}
lsttxtSetting = ['1', '2','3 ','4','5 ','6','7','8','9','10']
for t in range(10):
txtName=txtNameGroupTS+str(t)
if t == 0:
txtPlaceY=120
else:
txtPlaceY=txtPlaceY+30
self.txtWidget[txtName] = Text(self.groupSettingFrame,height=1, width=10,borderwidth = 2)
self.txtWidget[txtName].insert(INSERT, lsttxtSetting[t])
self.txtWidget[txtName].pack()
self.txtWidget[txtName].place(x=200, y = txtPlaceY)
except IOError:
print "Error: Group Settings Popup error"
def turbDataTransferBind(self):
for P in range(0,3):
boxName="boxSetting"+str(X)
dataSettingbox=self.lstTurb[X]+" "+self.boxWidget[boxName].get()
self.root_node_Setting = self.tree.insert( self.root_node_ChildSetting["ChildSettingNode"], 'end', text=dataSettingbox, open=True)
def treeDataTransfer(self,dlgTurbFlag):
self.treeDataTransferBind()
print "data tranfer sucess"
def deleteTreeNodes(self):
print "delete nodes"
command= and bind expect function name - without () and arguments - so in place of
If you use
.bind("<<ComboboxSelected>>", invoke_Setting_Group(self) )
then you use result from invoke_Setting_Group(self) as second argument in .bind(). This way you could dynamicly generate function used as argument in bind
TypeError: () takes no arguments (1 given)
This means you have function function() but python run it as function(arg1)
You run lambda:invoke_Setting_Group(self) but python expects lambda arg1:self.invoke_Setting_Group(self)
You could create function with extra argument
def invoke_My_method1(self, event):
print "expand another window"
print "event:", event, event.widget, event.x, event.y
And then you could use it
.bind("<<ComboboxSelected>>", lambda event:invoke_Setting_Group(self, event))
BTW: it looks strange - you have class App() but in second file you use only functions instead of some class too.

Python Object contains list of another object throws AttributeError

Python version 3.3 w/ Aptana IDE
I'm teaching myself python in my spare time at work so I decided to recreate a poker game that my friends and I play. To facilitate the various calls to different functions I created two objects. One object contains the data for the entire game, GameData, and the second object contains a single player, Player, that I am attempting to add to GameData.
The below code loops and attempts to add Player to a list in GameData but I get an error stating:
AttributeError: type object 'GameData' has no attribute 'players'
class Player(object):
def __init__(self, seat):
self.seat = seat
self.chips = 0
self.wins = 0
self.card = 0
self.isDealer = False
class GameData(object):
def __init__(self):
self.games = 0
self.numPlayers = 0
self.chips = 0
self.players = []
self.deck = []
The below function throws the error
def testDealCards():
gd = nuts.GameData #declare GameData object
gd.deck = [7,5,5,5,3,1,5,6,1,2] #assign values to deck list
for x in range(2): #loop to create player objects in GameData
gd.players.append(Player)
gd.players[0].isDealer = True
gd.players[1].isDealer = False
print(gd.players)
nuts.dealCards(gd)
assert gd.players[0].card == 5
assert gd.players[1].card == 7
pass
You are accessing the GameData class type instead of creating an object.
Try this:
gd = nuts.GameData()