Python: How to access instance member from other module? - python

I'm a beginner struggling with calling an instance member from another module. My code is quite long, but I can reproduce the issue with this snippet:
mainmodule.py:
from othermodule import *
class Class2_in_main():
mystring = 'Initial Value'
print mystring
def change_string(self, NewStringValue):
self.mystring = NewStringValue
print self.mystring
def main():
MyObjectInstance = Class2_in_main()
Object2 = othermodule.Class_in_othermodule()
if __name__ == '__main__':
main()
othermodule.py:
from mainmodule import *
class Class_in_othermodule():
MyObjectInstance().change_string('New String Value!')
Here's my stack:
Initial Value
Traceback (most recent call last):
File "mainmodule.py", line 1, in <module>
from othermodule import *
File "C:\PythonScripts\StackOverflowExample\othermodule.py", line 3, in <module>
class Class_in_othermodule():
File "C:\PythonScripts\StackOverflowExample\othermodule.py", line 6, in Class_in_othermodule
MyObjectInstance().change_string('New String Value!')
NameError: name 'MyObjectInstance' is not defined
I use Python 2.7.
Any idea? I'm sorry for the bad formatting, it's my first question here, and I can't figure out how that works!
Update: I was able to have my code working, but I would like to understand how to call "change_string" specifically for my instance only (called MyObjectInstance), how could I do that?? Here is what I currently have:
mainmodule.py:
import othermodule
class Class2_in_main():
mystring = 'Initial Value'
print mystring
def change_string(self, NewStringValue):
self.mystring = NewStringValue
print self.mystring
def main():
global MyObjectInstance
MyObjectInstance = Class2_in_main()
Object2 = othermodule.Class_in_othermodule()
if __name__ == '__main__':
main()
othermodule.py:
class Class_in_othermodule():
mainmodule.Class2_in_main().change_string('New String Value!')

Related

Python Calling a function within a class, within a function, from an imported module

I have this problem. I have 2 files at the moment. I am trying to print the words "Hello World Trudy". I can't get around doing it. It keeps telling me I have an attribute error. What should I do to fix it?
Traceback (most recent call last):
File "C:\Users\Trudy\Desktop\PythonLearning\test2.py", line 7, in <module>
f.sayHello()
AttributeError: 'NoneType' object has no attribute 'C'
test1.py
def main():
class C:
def function6(self):
print ("Hello")
def function7(self):
print ("Trudy")
def sayHello():
C().function6()
def sayWorld():
C().function7()
if __name__ == "__main__":
main()
test2.py
import test1
def function2():
print ("World")
test1.main().C.function6()
function2()
You don't need a main function in test1 file. Just have the Class C in there.
test1.py
class C:
def function6(self):
print ("Hello")
def function7(self):
print ("Trudy")
def sayHello():
C().function6()
def sayWorld():
C().function7()
test2.py
import test1
def function2():
print ("World")
test1.C().function6()
function2()

TypeError: 'dict' object is not callable from main

I wrote a code which is going to store occurrences of words from a text file and store it to a dictionary:
class callDict(object):
def __init__(self):
self.invertedIndex = {}
then I write a method
def invertedIndex(self):
print self.invertedIndex.items()
and here is how I am calling:
if __name__ == "__main__":
c = callDict()
c.invertedIndex()
But it gives me the error:
Traceback (most recent call last):
File "E\Project\xyz.py", line 56, in <module>
c.invertedIndex()
TypeError: 'dict' object is not callable
How can I resolve this?
You are defining a method and an instance variable in your code, both with the same name. This will result in a name clash and hence the error.
Change the name of one or the other to resolve this.
So for example, this code should work for you:
class CallDict(object):
def __init__(self):
self.inverted_index = {}
def get_inverted_index_items(self):
print self.inverted_index.items()
And check it using:
>>> c = CallDict()
>>> c.get_inverted_index_items()
[]
Also check out ozgur's answer for doing this using #property decorator.
In addition to mu's answer,
#property
def invertedIndexItems(self):
print self.invertedIndex.items()
then here is how you'll cal it:
if __name__ == "__main__":
c = callDict()
print c.invertedIndexItems
Methods are attributes in Python, so you can't share the same name between them. Rename one of them.

How to import a variable from another function and another class?

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

why I can't update a variable value and return self.func(*args)?

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.

Class data attribute not being accessible in class method

I have written a small program that will print all the files and directories inside the path specified by me. The source code is:
import os
import glob
class FolderStats:
targetdir = ""
def __init__(self, dirpath = None):
targetdir = dirpath
totalfiles = 0
totalsubfolders = 0
def FolderIterator(self):
print self.targetdir
listing = os.listdir(self.targetdir)
for infile in listing:
print "current file is: %s" % (infile)
if __name__ == '__main__':
Obj = FolderStats(raw_input('Enter your path: '))
Obj.FolderIterator()
The above code is not executing. I am getting an error in the method FolderIterator: when the print command is executed, it prints nothing. <targetdir> no more contains the path supplied by me. Why is it so?
In your __init__ you need to use self.targetdir instead of targetdir
>>> class Test:
var = 1
def __init__(self):
var = 2
print self.var # Object variable
print var # Local variable
def func(self):
print self.var
print var # this will fail, because there's no local var in this scope
>>> a = Test()
1
2
>>> a.func()
1
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
a.func()
File "<pyshell#10>", line 9, in func
print var
NameError: global name 'var' is not defined

Categories

Resources