Class does not pass the self variables to functions inside of it - python

I am a newbie programmer
I am defining this simple class but I receive the following error
I am not able to understand what im doing wrong
from PIL import Image
class PreProcessing(object):
def __init__(self,NAME):
super(PreProcessing,self).__init__()
self.name = NAME
self.newsize = 512
PATH = '/home/alireza/Desktop/ssd'
self.pathImage = PATH + '/' + self.name + '.jpg'
self.pathAnn = PATH + '/' + self.name + '.xml'
def image_loader(self):
print(self.pathImage )
When I call
NAME = '002498'
PreProcessing.image_loader(NAME)
, i get this error:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-38-5747710fa005> in <module>()
3 sizee = [1, 3, 375, 500]
4 # A= PreProcessing(NAME)
----> 5 PreProcessing.image_loader(NAME)
<ipython-input-37-5f788218f7e3> in image_loader(self)
10
11 def image_loader(self):
---> 12 print(self.pathImage )
AttributeError: 'str' object has no attribute 'pathImage'

As #kindall said in his comment, you aren't making an instance of your class. It'll work if you set it up like this, creating a "hello" object of class PreProcessing():
from PIL import Image
class PreProcessing(object):
def __init__(self,NAME):
super(PreProcessing,self).__init__()
self.name = NAME
self.newsize = 512
PATH = '/home/alireza/Desktop/ssd'
self.pathImage = PATH + '/' + self.name + '.jpg'
self.pathAnn = PATH + '/' + self.name + '.xml'
def image_loader(self):
print(self.pathImage )
NAME = "12345"
hello = PreProcessing(NAME)

Related

'str' object has no attribute 'url'

I've looked through several articles on this topic but I could not figure out any way to adapt this to my scenario. I'm running this code in python3 console:
### API MANAGER ###
import requests, time, pandas as pd
class api_manager():
#from ipython.display import display, HTML
def __init__(self, api_identifier = 1):
test_api = "570/"
live_api = "205790/"
self.heroes = []
self.items = []
self.token = ""
self.api = ""
self.url = "https://api.steampowered.com/"
if api_identifier == 1:
self.api = live_api
else:
self.api = test_api
self.get_access_token()
self.initialize_heroes()
self.initialize_items()
pass
def get_access_token(self):
with open("conf/access.config") as file:
self.token = file.read().split(":")[1]
file.close()
pass
def initialize_heroes(self):
api_method = "IEconDOTA2_"
response = requests.get(self.url + api_method + self.api + "GetHeroes/v1/?format=JSON&language=en_us&key=" + self.token)
hero_list = response.json()
for hero_id in range(len(hero_list['result']['heroes'])):
self.heroes.append([hero_list['result']['heroes'][hero_id]['id'], hero_list['result']['heroes'][hero_id]['localized_name'], hero_list['result']['heroes'][hero_id]['name'].replace('npc_dota_hero_', "").replace("_", " ")])
#self.heroes.sort()
#heroes_df = self.pd.DataFrame(self.heroes, columns=["ID", "Hero", "Hero Tag"])
#self.pd.set_option('display.max_colwidth', -1)
#display(HTML(heroes_df.to_html(index = False)))
pass
def initialize_items(self):
api_method = "IEconDOTA2_"
response = requests.get(self.url + api_method + self.api + "GetGameItems/v1/?format=JSON&language=en_us&key=" + self.token)
item_list = response.json()
for item_id in range(len(item_list['result']['items'])):
self.items.append([item_list['result']['items'][item_id]['id'], item_list['result']['items'][item_id]['localized_name'], item_list['result']['items'][item_id]['name']])
#self.items.sort()
#items_df = self.pd.DataFrame(self.items, columns=["ID", "Item", "Item Tag"])
#self.pd.set_option('display.max_colwidth', -1)
#display(HTML(items_df.to_html(index = False)))
pass
def get_match_details(match_id, self):
api_method = "IDOTA2Match_"
response = requests.get(self.url + api_method + self.api + "GetMatchDetails/V001/?format=JSON&language=en_us&key=" + self.token + "&match_id=" + str(match_id))
print(response.json())
pass
def get_match_details_in_range(match_id, match_id_upper_bound, self):
api_method = "IDOTA2Match_"
for next_match_id in range(match_id, match_id_upper_bound):
response = requests.get(self.url + api_method + self.api + "GetMatchDetails/V001/?format=JSON&language=en_us&key=" + self.token + "&match_id=" + str(next_match_id))
print(response.json())
time.sleep(1.05)
pass
def __str__(self):
return self.url + " " + self.api
def __repr__(self):
return self.url + " " + self.api
And I'm getting this error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "E:\Dropbox\DotA 2 WebAPI Development\Executable Python Files\dota_api_manager.py", line 77, in get_match_details
response = requests.get(self.url + api_method + self.api + "GetMatchDetails/V001/?format=JSON&language=en_us&key=" + self.token + "&match_id=" + str(match_id))
AttributeError: 'str' object has no attribute 'url'
I have tried different things like moving the import statement into the class and stuff like that and also tried implementing __str__() and __repr__() as suggested in this post but I couldn't get this to work. I'm fairly new to Python so it might be that there's something obvious that I just overlooked. Thanks in advance for you help and let me know if there's any additional information you could need!

TypeError: __init__() got an unexpected keyword argument 'dir'

I try to start a timer to do some file arvchival job. the code is like this:
from threading import Timer
message_archive_dir = "achivedir"
message_archive_format = "zip"
archive_timer = Timer(86400, messageachiver.archive, dir = message_archive_dir, fmt = message_archive_format)
archive_timer.start()
class messageachiver(object):
def __init__(self, **kwargs):
self.message_archive_dir = dir
self.message_archive_format = fmt
def archive(self):
print("message_archive_dir is " + self.message_archive_dir)
print("message_archive_format is " + self.message_archive_format)
print("Archiving trade messages")
I got below error:
Traceback (most recent call last):
File "sa_listener.py", line 43, in <module>
archive_timer = Timer(archive_interval, messageachiver.archive, dir = message_archive_dir, fmt = message_archive_format)
TypeError: __init__() got an unexpected keyword argument 'dir'
I'm not sure why _init_ does not accept **kwargs.
This specific init error is because you are passing multiple variables to the timer class.
In this line:
Timer(86400, messageachiver.archive, dir = message_archive_dir, fmt = message_archive_format)
You are passing the archive function, the dir variable, and the fmt variable to TIMER and not to the messageachiver class. Timer has no named variables for dir and fmt.
So the line should be Timer(86400, messageachiver.archive)
This only partially fixes your problem though. Because you are never actually initializing the class with the variables you need them to have. So before you call timer, you need to initialize the class messageachiver by adding mymessageachiver = messageachiver(dir = message_archive_dir, fmt = message_archive_format)
Also you need to put your class definition before you try to initialize it.
The final code:
from threading import Timer
class messageachiver(object):
def __init__(self, **kwargs):
self.message_archive_dir = kwargs['dir']
self.message_archive_format = kwargs['fmt']
def archive(self):
print("message_archive_dir is " + self.message_archive_dir)
print("message_archive_format is " + self.message_archive_format)
print("Archiving trade messages")
message_archive_dir = "achivedir"
message_archive_format = "zip"
mymessageachiver = messageachiver(dir = message_archive_dir, fmt = message_archive_format)
# That's a huge wait time, try something like 10 for a smaller wait during testing.
archive_timer = Timer(86400, mymessageachiver.archive)
archive_timer.start()

.items() doesn't work in my created class

I wrote this script:
class MonDictionnaire:
def __init__(self):
self.dictionnaire = {}
def __add__(self, objetàajouter):
nouvelle_valeure = MonDictionnaire()
nouvelle_valeure.dictionnaire = self.dictionnaire
nouvelle_valeure.dictionnaire = dict(self.dictionnaire.items() + objetàajouter.items()
then I wanted two objects in this class like:
>>>>fruit = MonDictionnaire()
>>> fruit.dictionnaire["pommes"] = 13
>>> fruit.dictionnaire["poires"] = 12
>>> fruit.dictionnaire["pruneau"] = 11
>>> legume = MonDictionnaire()
>>> legume.dictionnaire["poireau"] = 10
>>> legume.dictionnaire["panet"] = 9
then I just wanted to add my two objects like:
>>> fruit = fruit + legume
but the shell return me the following error message:
Traceback (most recent call last):
File "<pyshell#39>", line 1, in <module>
fruit = fruit + legume
File "D:\Python\Dictionnaire.py", line 9, in __add__
nouvelle_valeure.dictionnaire = dict(self.dictionnaire.items() + objetàajouter.items())
AttributeError: 'MonDictionnaire' object has no attribute 'items'
and I don't get why as my created class is a dictionnary???!!!
thank you so much for helping me!!!
Looks like your issue is with this line:
nouvelle_valeure.dictionnaire = dict(self.dictionnaire.items() + objetàajouter.items()
When you call: fruit = fruit + legume your class is trying to call .items() on legume. I think this change should work as you expect:
nouvelle_valeure.dictionnaire = dict(self.dictionnaire.items() + objetàajouter.dictionnaire.items()
You have defined the instance attribute:
self.dictionnaire = {}
whereas in objetàajouter.items() you're trying to get the items method of the instance itself, which is not present.
You need to explicitly specify the attribute:
objetàajouter.dictionnaire.items()
Also, were you meant to subclass dict?

How to select import object name from another function

EDIT: I have managed to solved the issue I wa having previously but instead of me creating another new question, this issue I have encountered are pretty much similar I guess?
As I am modifying some of the contents of this script that I am currently doingn, it will boot up this UI whenever user imports in a .chan object
Currently I am trying to edit the camera name such that when users selects the camera, it will inherits the name of the imported camera into its namespace.
Though I am not very sure, I think the reader function in the customNodeTranslator class is the one that reads the imported camera?
This is the error messgae:
# Error: global name 'cameraName' is not defined
# Traceback (most recent call last):
# File "/user_data/scripts/test/maya/plugins/chan.py", line 210, in readFileIn
# self.importTheChan = ChanFileImporter(chanRotationOrder)
# File "/user_data/scripts/test/maya/plugins/chan.py", line 286, in __init__
# self.cameraName = cameraName
# NameError: global name 'cameraName' is not defined #
This is the original code:
class customNodeTranslator(OpenMayaMPx.MPxFileTranslator):
...
...
...
def reader(self, fileObject, optionString, accessMode):
self.initialWindow()
try:
fullName = fileObject.fullName()
print ">>> full Name is %s" %fullName
#self.fileHandle = open(fullName,"r")
camHandle = open(fullName,"r")
camPath = os.path.basename(camHandle.name)
camName = os.path.splitext(camPath)[0]
print ">>> This is the name: %s" % camName
except:
sys.stderr.write( "Failed to read file information\n")
raise
return camName
class chanImport():
""" importing chan camera from nuke """
def __init__(self, rotation):
self.rotation = rotationOrder
# create the camera
self.cameraName = cmds.camera(n=str(camName))
self.cameraShape = self.cameraName[1]
cmds.select(self.cameraShape)
cmds.scale(0.5, 0.5, 0.5)
The following code is the actual code itself before I modified:
class customNodeTranslator(OpenMayaMPx.MPxFileTranslator):
...
...
...
def writer( self, fileObject, optionString, accessMode ):
try:
fullName = fileObject.fullName()
fileHandle = open(fullName,"w")
selectList = OpenMaya.MSelectionList()
OpenMaya.MGlobal.getActiveSelectionList(selectList)
node = OpenMaya.MObject()
depFn = OpenMaya.MFnDependencyNode()
path = OpenMaya.MDagPath()
iterator = OpenMaya.MItSelectionList(selectList)
animationTime = OpenMayaAnim.MAnimControl()
class ChanFileImporter():
def __init__(self, rotationOrder):
self.rotationOrder = rotationOrder
# create the camera
self.cameraName = cmds.camera()
self.cameraShape = self.cameraName[1]
cmds.select(self.cameraShape)
cmds.scale(0.5, 0.5, 0.5)
You aren't passing the camName to the importer class. In fact you're not invoking the importer class at all in the sample above.
If you modify chanImport so it takes the name you want:
class chanImport(object):
""" importing chan camera from nuke """
def __init__(self, camName):
self.desiredCameraName = camName
self.cameraName = None
self.cameraShape = None
def create_camera(self):
self.cameraName, self.cameraShape = cmds.camera(n=str(camName))
cmds.select(self.cameraShape)
cmds.scale(0.5, 0.5, 0.5)
return self.cameraName
You should be able to invoke it inside your reader function:
def reader(self, fileObject, optionString, accessMode):
self.initialWindow()
try:
fullName = fileObject.fullName()
print ">>> full Name is %s" %fullName
camHandle = open(fullName,"r")
camPath = os.path.basename(camHandle.name)
camName = os.path.splitext(camPath)[0]
print ">>> This is the name: %s" % camName
importer = chanImport(camName)
actual_cam_name = importer.create_camera()
print ">>> created " + actual_cam_name
return actual_cam_name
except:
sys.stderr.write( "Failed to read file information\n")
raise

Python - global name is not defined when calling function from class __init__ method

I am new to Python and working on a class for storing meaningful data pieces about books. I have started as follows:
class BookDisplay:
def __init__(self, _name, _isbn, _price, _picture, _link):
self.name = _name
self.isbn = _isbn
self.price = _price
self.picture = _picture
self.link = _link
self.xmlString = MakeXMLString(_name, _isbn, _price, _picture, _link)
name = ""
isbn = ""
price = 0.0
picture = "" #a URL
link = ""
xmlString = ""
I thought this __init__ method would just be able to call MakeXMLString, which I defined in the same file (bookdisplay.py), right below the BookDisplay class:
def MakeXMLString(_name, _isbn, _price, _picture, _link): #python multi-line syntax
xmlString = "<name>" + _name + "</name>" \
+ "<isbn>" + _isbn + "</isbn>" \
+ "<price>" + str(_price) + "</price>" \
+ "<picture>" + _picture + "</picture>" \
+ "<link>" + _link + "</link>"
return xmlString
Originally, I actually had MakeXMLString as a method within the class, like this:
def MakeXMLString(self):
self.xmlString = "<name>" + self.name + "</name>" \
+ "<isbn>" + self.isbn + "</isbn>" \
+ "<price>" + str(self.price) + "</price>" \
+ "<picture>" + self.picture + "</picture>" \
+ "<link>" + self.link + "</link>"
In that case, __init__ contained this call:
self.xmlString = self.MakeXMLString()
In both cases, when trying to instantiate BookDisplay from another file:
from bookdisplay import BookDisplay
...
...
thumbnails = []
...
thumbnails.append(BookDisplay(titleField, "-1", float(priceField), imgField, linkField))
...I get the following global name error (this traceback in particular for the not-within-class function):
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "search.py", line 30, in ebaySearch
handleDocument(doc)
File "search.py", line 59, in handleDocument
handleItems(items, outputFile)
File "search.py", line 102, in handleItems
thumbnails.append(BookDisplay(titleField, "-1", float(priceField), imgField, linkField))
File "bookdisplay.py", line 15, in __init__
self.xmlString = MakeXMLString(_name, _isbn, _price, _picture, _link)
NameError: global name 'MakeXMLString' is not defined
What am I missing here? From what I can tell, MakeXMLString is perfectly accessible to the class.
when you defined MakeXMLString as a method, it is not returning anything so
self.xmlString = self.MakeXMLString()
will overwrite self.xmlString and make it point to the method itself.
With the way you have it defined now, MakeXMLString is not accessible from the other file, so you have to manually import it as well by doing:
from bookdisplay import BookDisplay, MakeXMLString
EDIT:
upon rereading, you aren't calling MakeXMLString from the other file, so the error is in bookDisplay.py; make sure
def MakeXMLString()
is on the same indent level as the class definition, otherwise it'll be interpreted as a method.

Categories

Resources