I'm trying but it's not working. I have the following code line:
class Run:
def Method(self, choice):
print "%sZip :\t%s%s\n".decode('utf-8') % (Basic_Green, White, choice.start().LoadJson['zip'])
And this is variable, and is within another class, and another function:
class Host_Method:
def start(self):
My_API = requests.get("http://ip-api.com/json/%s" % socket.gethostbyname(sys.argv[2]))
LoadJson = json.loads(My_API.content)
The error:
Traceback (most recent call last):
File "InfoIP.py", line 78, in <module>
elif sys.argv[1] == "-h": Run().Method(Host_Method())
File "/Pentest/InfoIP2/Libraries/InfoIP_Functions.py", line 159, in Method
print "%sZip :\t%s%s\n".decode('utf-8') % (Basic_Green, White, choice.LoadJson['zip'])
AttributeError: Host_Method instance has no attribute 'LoadJson'
You probably want them to be stored in an instance variable (self....). And you probably want your start to be an __init__ method. Your corrected class could look like:
class HostMethod:
def start(self):
self.my_API = requests.get("http://ip-api.com/json/{0}".format(socket.gethostbyname(sys.argv[2])))
self.load_json = json.loads(self.my_API.content)
Then, you could do:
class Run:
def Method(self, choice):
print "{0}Zip :\t{1}{2}\n".decode('utf-8').format(Basic_Green, White, choice.load_json['zip'])
a = Run()
a.method(HostMethod())
See also:
https://docs.python.org/3.4/tutorial/classes.html
Related
First, I am using python 3.6.
I am trying import and use my own .py file in my project. I import my LinkedList.py file and create a Mylist class, which extends the imported file's class.
When I try the construct an instance of the Mylist class, which involves creating an instance of my inheritedLinkedList derived class, I get the following error:
Traceback (most recent call last):
File "*/PycharmProjects/Veri Yapilari/lists.py", line 65, in <module>
test = Mylist()
File "*/PycharmProjects/Veri Yapilari/lists.py", line 38, in __init__
self.linkedlist = inheritedLinkedList()
File "*/PycharmProjects/Veri Yapilari/lists.py", line 8, in __init__
super.__init__()
TypeError: descriptor '__init__' of 'super' object needs an argument
Here's the section of the code where the problem occurs:
test = Mylist()
test.insertFirstM(incomingDataM=4) # <- Causes a TypeError.
Below is the main script in its entirety:
import LinkedList as myLinkedList
class inheritedLinkedList(myLinkedList.DoublyLinkedList):
def __init__(self):
super.__init__()
def raplaceElements(self, dataToBeChanged, incomingData):
position = self.find(dataToBeChanged)
position.data = incomingData
def swapElements(self, swap1, swap2):
position1 = self.find(swap1)
prev1 = position1.previous
next1 = position1.next
position2 = self.find(swap2)
prev2 = position2.previous
next2 = position2.next
prev1.next = position1
position1.previous = prev1
position1.next = next1
next1.previous = position1
prev2.next = position2
position2.previous = prev2
position2.next = next2
next2.previous = position2
def insertBefore(self, incomingData, previousNode=None):
self.insert(incomingData, self.find(previousNode).previous.data)
class Mylist:
def __init__(self):
# self.linkedlist = inheritedLinkedList;
self.linkedlist = inheritedLinkedList() # Per martineau's suggestion.
def replaceElements(self, dataToBeChanged, incomingData):
self.linkedlist.raplaceElements(dataToBeChanged, incomingData)
def swapElements(self, swap1, swap2):
self.linkedlist.swapElements(swap1, swap2)
def insertFirstM(self, incomingDataM):
self.linkedlist.insertFirst(incomingDataM)
def insertLast(self, incomingData):
self.linkedlist.insert(incomingData)
def insertAfter(self, incomingData, incomingNode):
self.linkedlist.insert(incomingData, incomingNode)
def insertBefore(self, incomingData, incomingNode):
self.linkedlist.insert(incomingData, incomingNode)
def remove(self, incomingData):
self.linkedlist.remove(incomingData)
def listprint(self):
self.linkedlist.listprint()
test = Mylist()
test.insertFirstM(4)
The code for the imported LinkedList module (LinkedList.py) can be obtained—if needed—by downloading it from my github repository.
As I said in a comment, you're not using the super built-in correctly. Try do things this way instead (so it's like the example in the linked documentation):
class inheritedLinkedList(myLinkedList.DoublyLinkedList):
def __init__(self):
super().__init__() # Change line to this.
Actually, since the derived class' __init__() is currently doing nothing but that, it's not even necessary because that's what would occur automatically if the subclass didn't define its own. In other words, the following would accomplish the same thing:
class inheritedLinkedList(myLinkedList.DoublyLinkedList):
# ** NOT REALLY NEEDED AT ALL **
# def __init__(self):
# super().__init__()
P.S. You also ought to change the very end of the LinkedList.py script so the last few lines that are there don't execute when it's imported as a module by lists.py:
...
nextNode.previous = previousNode
dataToBeDeleted.next = dataToBeDeleted.previous = None
if __name__ == '__main__': # Should add this, too.
list1 = SinglyLinkedList()
list2 = DoublyLinkedList()
list2.insertFirst(6)
I'm trying to use Python's unittest module to compare results and expected values and get test statistics in the end. However, below sample code gives me the following error:
File "...", line 16, in <module>
run_tests.test_equal()
File "...", line 13, in test_equal
self.assertEqual(self.result, self.expected)
File "/usr/lib/python2.7/unittest/case.py", line 512, in assertEqual
assertion_func = self._getAssertEqualityFunc(first, second)
File "/usr/lib/python2.7/unittest/case.py", line 493, in _getAssertEqualityFunc
asserter = self._type_equality_funcs.get(type(first))
AttributeError: 'RunTests' object has no attribute '_type_equality_funcs'
Sample code:
import unittest
class RunTests(unittest.TestCase):
def __init__(self, result, expected):
self.result = result
self.expected = expected
def runTest(self):
test_equal(self)
def test_equal(self):
self.assertEqual(self.result, self.expected)
run_tests = RunTests(9, 9)
run_tests.test_equal()
if __name__ == '__main__':
unittest.main()
How can I use the module's comparison functions on varying input values? I have found this post, but the problem appears to be different.
Thanks a lot in advance.
You skipped the call of __init__ of a base class inside your RunTests.__init__, which takes care of defining _type_equality_funcs.
def __init__(self, result, expected):
super().__init__()
self.result = result
self.expected = expected
you need to call __init__ method of base class.
this might be useful :
import unittest
class RunTests(unittest.TestCase):
def __init__(self, *args, **kwargs):
super(RunTests, self).__init__()
def runTest(self):
self.test_equal()
def test_equal(self):
self.assertEqual(9, 9)
run_tests = RunTests()
run_tests.test_equal()
if __name__ == '__main__':
unittest.main()
I'm sending a variable value from programa1 for a new object using :
def send_price(self):
self.pricesend = float(self.text1.get()) #this take a value from a tkinker.Entry
print(self.pricesend)
objetoprograma1.Object(self.pricesend)
the object "objetoprograma1" return a new value using:
class Object():
def __init__(self, price):
self.price_recibe = float(price)
print(self.price_recibe)
self.new_price = self.price_recibe + 10
print(self.new_price)
programa1.Aplication.recibe_newprice(self, float(self.new_price))
now I want to update the value in the principal1 tkinter.Entry called self.text1:
def recibe_newprice(self, new_price):
self.new_price = new_price
print("price new recibe" , self.new_price)
## this don't work.. this don't update or change the value in the tkinter.Entry
self.text1.delete(0, len(self.text1.get()))
self.text1.insert(self.my_main, str(self.new_price))
I have the following exception:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python34\lib\tkinter\__init__.py", line 1482, in __call__
return self.func(*args)
File "B:\MAESTRIA\PYTHON\trabajos\hello\programa1.py", line 38, in send_price
objetoprograma1.Object(self.pricesend)
File "B:\MAESTRIA\PYTHON\trabajos\hello\objetoprograma1.py", line 19, in __init__
programa1.Aplication.recibe_newprice(self, float(self.new_price))
File "B:\MAESTRIA\PYTHON\trabajos\hello\programa1.py", line 51, in recibe_newprice
self.text1.delete(self.my_main, len(self.text1.get()))
AttributeError: 'Object' object has no attribute 'text1'
the full programa1.py
# -*- coding: latin-1 -*-
import tkinter
import objetoprograma1
import time
class Aplication():
def __init__(self,my_main):
self.my_main = my_main
self.variables()
self.GUI()
def variables (self):
self.price = None
self.list = []
def GUI(self):
self.text1 = tkinter.Entry()
self.text1.insert(0, "1000")
self.text1.grid(column = 0, row = 0)
self.boton1 = tkinter.Button(self.my_main, text = "sendprice", command = self.send_price )
self.boton1.grid(column=1, row = 0)
def send_price(self):
self.pricesend = float(self.text1.get())
print(self.pricesend)
objetoprograma1.Object(self.pricesend)
def recibe_newprice(self, new_price):
self.new_price = new_price
print("price new recibe" , self.new_price)
## this don't work
self.text1.delete(0, len(self.text1.get()))
self.text1.insert(self.my_main, str(self.new_price))
if __name__ == "__main__":
root = tkinter.Tk()
#root.geometry("800x500+0+0")
root.title("titulo")
app = Aplication(my_main=root)
root.mainloop()
and objetoprograma1.py
# -*- coding: latin-1 -*-
import programa1
import tkinter
import time
class Object():
def __init__(self, price):
self.price_recibe = float(price)
print(self.price_recibe)
self.new_price = self.price_recibe + 10
print(self.new_price)
programa1.Aplication.recibe_newprice(self, float(self.new_price))
Look at your Object class and look at the exception message. You are calling the recibe_newprice method, but passing it the Object instance (Object has no text1 attribute). The recibe_newprice is written for the Aplication class and as such expects self to be an instance of the Aplication class. You seem to be mixing up what classes are for or how the self argument works.
My first tip is to name things with more descriptive names. Names like Object, Application, and Program1 don't tell the reader anything about what the purpose of those objects are.
Second, do you know the difference between classes and functions? Maybe this will help. I would code the send_price method this way:
def send_price(self, price_recibe):
pricesend = float(self.text1.get())
print(pricesend)
print(price_recibe)
new_price = price_recibe + 10
print(new_price)
self.recibe_newprice(new_price)
If this doesn't make sense why I'm doing things this way or why this might be considered better/easier than the way you did it then I suggest researching how python classes, attribute assignment, and argument passing works.
I am new in Python and I wrote the following code:
class Frazione:
def __init__(self, Numeratore, Denominatore=1):
mcd=MCD(Numeratore,Denominatore)
self.Numeratore=Numeratore/mcd
self.Denominatore=Denominatore/mcd
def MCD(m,n):
if m%n==0:
return n
else:
return MCD(n,m%n)
def __str__(self):
return "%d/%d" %(self.Numeratore, self.Denominatore)
def __mul__(self, AltraFrazione):
if type(AltraFrazione)==type(5):
AltraFrazione=Frazione(AltraFrazione)
return Frazione(self.Numeratore*AltraFrazione.Numeratore, self.Denominatore*AltraFrazione.Denominatore)
__rmul__=__mul__
Open shell at the same folder of Frazione.py:
>>> from Frazione import Frazione
end then
>>> f=Frazione(10,5)
When I press Enter, I receive this output:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File ".\Frazione.py", line 5, in __init__
mcd=MCD(Numeratore,Denominatore)
NameError: global name 'MCD' is not defined
PS. I apologize for my english!
MCD is a method of Frazione, but you're calling it as if it were a global function. The easiest (and cleanest, IMHO) fix is to just move it outside the class, because it doesn't need to access any class or instance members.
So:
def MCD(m, n):
if m % n == 0:
return n
else:
return MCD(n, m % n)
class Frazione:
# as before but without MCD
If you do want to keep it in the class, then you might rewrite it to be iterative instead of recursive and call it as self.MCD in __init__. That's a good idea anyway, as Python's support for recursion is rather weak.
I'm trying to use a global variable. I've declared it as global to begin with and the declare it at such at each mention, but I get a NameError after the first function completes. Here's the code, and I think I've gone stare crazy but I can't seem to find the problem.
def on_servername_insertatcursor(self, widget):
global output
output = StringIO.StringIO()
servername = widget.get_text()
output.write("USHARE_NAME="+servername+'\n')
def on_netif_changed(self, widget):
netif = widget.get_active_text()
global output
output.write("USHARE_IFACE="+netif+'\n')
def on_port_insertatcursor(self, widget):
global output
port = widget.get_text()
output.write("USHARE_PORT="+port+'\n')
def on_telprt_insertatcursor(self, widget):
global output
telprt = widget.get_text()
output.write("USHARE_TELNET_PORT="+telprt+'\n')
def on_dirs_insertatcursor(self, widget):
global output
dirs = widget.get_text()
output.write("USHARE_DIR="+dirs+'\n')
def on_iconv_toggled(self, widget):
global output
iconv = widget.get_active()
if iconv == True:
output.write("USHARE_OVERRIDE_ICONV_ERR="+"True"+'\n')
else:
output.write("USHARE_OVERRIDE_ICONV_ERR="+"False"+'\n')
def on_webif_toggled(self, widget):
global output
webif = widget.get_active()
if webif == True:
output.write("USHARE_ENABLE_WEB="+"yes"+'\n')
else:
output.write("USHARE_ENABLE_WEB="+"no"+'\n')
def on_telif_toggled(self, widget):
global output
telif = widget.get_active()
if telif == True:
output.write("USHARE_ENABLE_TELNET="+"yes"+'\n')
else:
output.write("USHARE_ENABLE_TELNET="+"no"+'\n')
def on_xbox_toggled(self, widget):
global output
xbox = widget.get_active()
if xbox == True:
output.write("USHARE_ENABLE_XBOX="+"yes"+'\n')
else:
output.write("USHARE_ENABLE_XBOX="+"no"+'\n')
def on_dlna_toggled(self, widget):
global output
dlna = widget.get_active()
if dlna == True:
output.write("USHARE_ENABLE_DLNA="+"yes"+'\n')
else:
output.write("USHARE_ENABLE_DLNA="+"no"+'\n')
def on_commit_clicked(self, widget):
commit = output.getvalue()
logfile = open('/home/boywithaxe/Desktop/ushare.conf','w')
logfile.write(commit)
def on_endprogram_clicked(self, widget):
sys.exit(0)
What's amazing is that when insertatcursor (coming from Gtk.TextBuffer.insert_at_cursor() ) is replace with activate, the code works perfectly, except I don't want to have the user have to press enter after every data input.
EDIT. The Traceback is as follows
Traceback (most recent call last):
File "/home/boywithaxe/Developer/Quickly/broadcast/broadcast/BroadcastWindow.py", line 58, in on_netif_changed
output.write("USHARE_IFACE="+netif+'\n')
NameError: global name 'output' is not defined
Having made the changes suggested by #jdi (Thank you btw, I see the logic behind that), the Traceback I get is as follows:
Traceback (most recent call last):
File "/home/boywithaxe/Developer/Quickly/broadcast/broadcast/BroadcastWindow.py", line 55, in on_netif_changed
OUTPUT.write("USHARE_IFACE="+netif+'\n')
NameError: global name 'OUTPUT' is not defined
Traceback (most recent call last):
File "/home/boywithaxe/Developer/Quickly/broadcast/broadcast/BroadcastWindow.py", line 72, in on_iconv_toggled
OUTPUT.write("USHARE_OVERRIDE_ICONV_ERR="+"True"+'\n')
NameError: global name 'OUTPUT' is not defined
Traceback (most recent call last):
File "/home/boywithaxe/Developer/Quickly/broadcast/broadcast/BroadcastWindow.py", line 79, in on_webif_toggled
OUTPUT.write("USHARE_ENABLE_WEB="+"yes"+'\n')
NameError: global name 'OUTPUT' is not defined
Traceback (most recent call last):
File "/home/boywithaxe/Developer/Quickly/broadcast/broadcast/BroadcastWindow.py", line 86, in on_telif_toggled
OUTPUT.write("USHARE_ENABLE_TELNET="+"yes"+'\n')
NameError: global name 'OUTPUT' is not defined
Traceback (most recent call last):
File "/home/boywithaxe/Developer/Quickly/broadcast/broadcast/BroadcastWindow.py", line 93, in on_xbox_toggled
OUTPUT.write("USHARE_ENABLE_XBOX="+"yes"+'\n')
NameError: global name 'OUTPUT' is not defined
Traceback (most recent call last):
File "/home/boywithaxe/Developer/Quickly/broadcast/broadcast/BroadcastWindow.py", line 100, in on_dlna_toggled
OUTPUT.write("USHARE_ENABLE_DLNA="+"yes"+'\n')
NameError: global name 'OUTPUT' is not defined
Traceback (most recent call last):
File "/home/boywithaxe/Developer/Quickly/broadcast/broadcast/BroadcastWindow.py", line 105, in on_commit_clicked
commit = OUTPUT.getvalue()
NameError: global name 'OUTPUT' is not defined
Your code example doesn't require a global. Just remove it. The only time you need to use the global keyword in a function is if you are going to assign to it.
OUTPUT = StringIO.StringIO()
def on_servername_insertatcursor(self, widget):
servername = widget.get_text()
OUTPUT.write("USHARE_NAME="+servername+'\n')
def on_netif_changed(self, widget):
netif = widget.get_active_text()
OUTPUT.write("USHARE_IFACE="+netif+'\n')
def on_port_insertatcursor(self, widget):
port = widget.get_text()
OUTPUT.write("USHARE_PORT="+port+'\n')
def on_telprt_insertatcursor(self, widget):
telprt = widget.get_text()
OUTPUT.write("USHARE_TELNET_PORT="+telprt+'\n')
def on_dirs_insertatcursor(self, widget):
dirs = widget.get_text()
OUTPUT.write("USHARE_DIR="+dirs+'\n')
def on_iconv_toggled(self, widget):
iconv = widget.get_active()
if iconv == True:
OUTPUT.write("USHARE_OVERRIDE_ICONV_ERR="+"True"+'\n')
else:
OUTPUT.write("USHARE_OVERRIDE_ICONV_ERR="+"False"+'\n')
Even if you wanted to be able to reset your StringIO object in a function, it still wouldn't require an assignment or global keyword:
def reset_output(self):
OUTPUT.seek(0)
OUTPUT.truncate()
Proof that it works
import StringIO
OUTPUT = StringIO.StringIO()
def foo():
OUTPUT.write('foo')
def bar():
OUTPUT.write('bar')
def print_output():
print OUTPUT.getvalue()
def reset_output():
OUTPUT.seek(0)
OUTPUT.truncate()
if __name__ == "__main__":
foo()
bar()
print_output()
reset_output()
print_output()
Output
$ python test.py
foobar
$
Try moving output = StringIO.StringIO() outside and above all the functions in the file.
Well, the problem with the question is unfortunate indenting :) Looking at PyGTK docs shows that the on_... functions shown are indeed methods of a class, not global functions, so the "global" variable is probably not really global but also a member of the class (just look at the self parameter in method definitions).
I gave a more detailed answer on askubuntu, here's a code snippet which shows what needs to be done:
class MyApp(gtk.Window):
output = None
def __init__(...):
...
self.output = StringIO.StringIO()
def on_servername_insertatcursor(self, widget):
servername = widget.get_text()
self.output.write("USHARE_NAME="+servername+'\n')
def on_netif_changed(self, widget):
netif = widget.get_active_text()
self.output.write("USHARE_IFACE="+netif+'\n')
There's absolutely no PyGTK-specific or signals-specific magic involved :)