I'm trying to call a different function inside the same class from my main function and I can seem to figure where the error is.
I keep getting this error relating to functions not being defined and I'm not sure how to resolve it:
NameError: global name 'results' is not defined
class Darts:
def main() :
print results()
def results() :
round_result_totals = "Stuff"
return round_result_totals
#RUNNING CODE
main()
Make sure that you define properly self in your functions and initialize an object first before you do anything else. You can't just call a function from a class without creating an instance of that class and calling a function from that instance (NOT THE CLASS). Usually you want to have an __init__ in your python classes.
class Darts:
def __init__(self):
pass
def main(self):
print(self.results())
def results(self):
round_result_totals = "Stuff"
return round_result_totals
Dart1 = Darts()
Dart1.main()
If you want to use variables, self is critical too for encapsulation.
class Darts:
def __init__(self):
self.a = 500
def main(self):
self.a += 1
print(self.a)
Dart1 = Darts()
Dart1.main()
You need to pass self (the instance of your object) into your object's methods.
class Darts:
def main(self) :
print self.results()
def results(self) :
round_result_totals = "Stuff"
return round_result_totals
You're missing all of the required references to self inside your class. It should look like this:
class Darts:
def main(self) :
print self.results()
def results(self) :
round_result_totals = "Stuff"
return round_result_totals
Here is the Python documentation on classes. And the fifth paragraph of this section makes reference to the convention of self.
Briefly: the first argument to a method of a Python class is automatically passed in a reference to the instance of that class from which the method is being called (provided it is being called as an instance method). This is done automatically by Python's interpreter. This parameter still needs to be explicitly stated in the method definition, however, and the convention is to call it self.
Related
We are using def for declaring variables and defining functions with
def myVariable
def getMyVar = {}
def getMyVariable () {}
What are these def defines? And how it identifies either function/ closure or method?
When using def keyword in Groovy, the actual type holder is Object so you can assign any object to variables defined with def, and return any kind of object if a method is declared returning def. def keyword is used for untyped variables whose type is defined dynamically at runtime.
Here are 3 definitions using def and the equivalent with Object as the type. The first defines an untyped variable and the second defines a variable assigned with an empty closure. The third defines the return type of a method.
def myVariable // Object myVariable
def getMyVar = {} // Object getMyVar = {}
def getMyVariable() {} // Object getMyVariable() {}
Note if assigning primitive number values (e.g int, float, etc.) to a def variable, it will auto-convert primitive types to an object instance of class Integer, Float, etc.
The Groovy Style Guide (#3 and #21) gives some guidelines on when to use optional typing with def and when to use explicit strong typing.
I'm developing a simple window that performs some operations at closure. This is my code extract:
from javax.swing import *
from java.awt import *
from java.awt.event import *
from java.io import *
import javax.swing.table.DefaultTableModel as DefaultTableModel
class registro(JFrame):
def __init__(self):
super(registro, self).__init__()
self.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
self.setExtendedState(JFrame.MAXIMIZED_BOTH)
#[...]
headers = ('Data e orario',
'Personale UO Q&A',
'Tipologia di attività '.decode('utf-8'),
'Personale incontrato con strutture di appartenenza',
'Note')
self.model = DefaultTableModel([["","","","",""]], headers)
self.table = JTable(self.model)
#[...]
self.addWindowListener(self.onClose())
#[...]
def onClose(self):
class saver(WindowAdapter):
tableModel = self.model
def windowClosing(self, event):
print tableModel #HERE IS THE ERROR!!!!!!!!!
return saver()
The error reported on the highlighted line is the following:
NameError: global name 'tableModel' is not defined
Although I have declared the variable inside the listener (to avoid misunderstanding between the two self), I don't understand why it has never been recognized. I'm almost a novice with object-oriented programming and Swing windows on Jython, and I hope this is not my (very) serious shortcoming!
Many thanks in advance.
There's a fairly subtle scope issue here, which is mostly about Python syntax, but also about what code you want to have access to the tableModel. The tableModel variable is not visible by default because you are inside the onClose() function. A defensive solution to this is to explicitly pass the needed variable into the new saver object. I personally prefer this as it more explicitly declares the inputs for saver objects.
class WindowAdapter:
None
class App:
def __init__(self):
self.model = 'DUMMYMODEL'
def onClose(self):
class Saver(WindowAdapter):
def __init__(self,tableModel):
WindowAdapter.__init__(self)
self.tableModel = tableModel
def windowClosing(self,event):
print (self.tableModel)
return Saver(self.model)
if __name__ == '__main__':
app = App()
sv = app.onClose()
sv.windowClosing(event=None)
(This code is cut down and in pure Python to show it is largely scoping related.)
An alternative would be using the Python global keyword to expose the tableModel variable to all lower scopes.
class WindowAdapter:
None
class App:
def __init__(self):
self.model = 'DUMMYMODEL'
def onClose(self):
global tableModel
tableModel = self.model
class Saver(WindowAdapter):
def windowClosing(self,event):
print (tableModel)
return Saver()
if __name__ == '__main__':
app = App()
sv = app.onClose()
sv.windowClosing(event=None)
I have a class definition which I have based on json.JSONEncoder, within which I have overriden the default method. Now when I call json.dumps on an instance of that class the default method is not being called? Is there something I have missed?
In my example code I do not expect this to magically produce the serialized object but I would expect the print("here") to be executed.
import json
class MyClass(json.JSONEncoder):
id = "myId"
data = "myData"
def default(self, o):
print("here")
print ("Create instance")
obj = MyClass()
print("Serialize")
print(json.dumps(obj))
print ("and done")
I am quite new to Python, so apologies if this is something horribly obvious.
After some further digging and tracing I think I have found the cause. Part of the issue I think it my own misunderstanding of how this is intended to be used.
When calling json.dumps if you wish to use a custom encoder you need to specify the class of that encoder, otherwise dumps defaults to using the standard implementation of JSONEncoder.
json.dumps(obj, cls=MyEncoder)
My misconception was that by basing my class on json.JSONEncoder that dumps would simply recognise the instance as inheriting from JSONEncoder and call the override default method. However this is not the case.
I have now created the logic in it's own class to encode my own class/types and when I call json.dumps I pass in that class name.
So I now have
class MyEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, MyClass):
return {"id": obj.id, "data": obj.data}
return json.JSONEncoder.default(self, obj)
And when I wish to serialize I use
json.dumps(object_to_serialize, cls=MyEncoder)
Which recognises my class and handles it, or passes on the encoding to the default encoder.
I have found following function calls in several frameworks which appear to me as if the framework extends some base classes. Some examples:
within(500 millis)
or
"Testcase description" in
{ .... }
First example returns a duration object with the duration of 500 milliseconds from akka and second is the definition of a testcase from scalatest.
I would like to know how this behavior is achieved and how it is called.
This is done with the "Pimp my library" technique.
To add non existing methods to a class, you define an implicit method that converts objects of that class to objects of a class that has the method:
class Units(i: Int) {
def millis = i
}
implicit def toUnits(i: Int) = new Units(i)
class Specs(s: String) {
def in(thunk: => Unit) = thunk
}
implicit def toSpecs(s: String) = new Specs(s)
See also "Where does Scala looks for Implicits?"
If I'm not mistaken, those pieces of code can be desugared as
within(500.millis)
and
"Testcase description".in({ ... })
This should make it easier to see what's going on.
What I want to know is, how can I create GUI elements using swing inside a Jython class so that they can be referenced from outside the class, and I can use statements like button.setText("Hello") on an object that was created inside another class. For example:
foo.py:
from javax.swing import *
class Test():
def __init__(self):
frame = JFrame("TEST")
button = JButton("Hey")
frame.add(button)
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
frame.setSize(300,200)
frame.show()
and then I have another file called somethingelse.py:
from foo import *
run = Test()
If I were to want to change the button text by using run.button.setText("Message"), how could I organise the Test() class such that I could change the text from the second file, somethingelse.py.
Your code is throwing away the references it has to the controls, so you can't access them from anywhere - frame and button are local variables, and disappear once __init__ returns.
You should (minimally) make them object members:
class Test():
def __init__(self):
self.frame = JFrame("TEST")
self.button = JButton("Hey")
self.frame.add(button)
# ...
You can then say:
from foo import *
run = Test()
run.button.setText("Message")