I'm trying to receive certain contents of a list called eeprom, and save them under a list called bytes.
class Parameter (object):
def __init__ (self, eeprom, *address):
self.eeprom = eeprom
self.bytes = list()
for a in address:
a = int(a, 16)
byte = eeprom[a] # here lies the problem
self.bytes.append(byte)
sthg = Parameter(eeprom, "0x00B9", "0x00BA")
Whenever I run the script, I get the following error:
TypeError: 'int' object has no attribute '__getitem__'
Does anyone has any idea of why this happens? If I write this on the interpreter it works, it is only when I run it as a module that I get this error.
When you are instantiating Parameter you are most likely passing an int in for the eeprom arguments instead of a list. You are probably doing the equivalent of
sthg = Parameter(1, "0x00B9", "0x00BA")
when you should be doing
sthg = Parameter([1,2,3,4], "0x00B9", "0x00BA")
When you are instantiating your class you should pass eeprom as a list argument but you are passing it as a int argument.
int object do not have any __getitem__() function that is why you can not access it using [] (indexing), so you should be having any iterable as a eeprom argument..
class Parameter (object):
def __init__ (self, eeprom, *address):
self.eeprom = eeprom
self.bytes = list()
for a in address:
a = int(a,16)
byte = eeprom[a] # here lies the problem
self.bytes.append(byte)
eeprom = [1,2,3,4,5,6,7,8,9,10,11]
sthg = Parameter(eeprom, "0x0009")
eeprom should be List object not integer an integer
Example:
eeprom = [1,2,3,4,5,6,7,8,9,10,11]
Related
I'm trying to first create an empty object and then assign variables to it with values. However, when I print the object variables, I discover they are of type tuple. Why aren't they just of type str or int for example?
I'm fairly new to Python so I might be missing something obvious to some.
Code that creates the object:
def getDbPoolConfig(self):
settingName = "pool"
dbConfig = EmptyObject()
dbConfig.host = settings.DATABASES[settingName]["HOST"],
dbConfig.port = settings.DATABASES[settingName]["PORT"],
dbConfig.user = settings.DATABASES[settingName]["USER"],
dbConfig.password = settings.DATABASES[settingName]["PASSWORD"],
dbConfig.dbName = settings.DATABASES[settingName]["NAME"]
return dbConfig
Code that uses the object and prints the object variables:
def dbConnect(self):
dbConfig = self.getDbPoolConfig()
print(dbConfig.host)
print(dbConfig.port)
print(type(dbConfig.port))
dbConnection = psycopg2.connect(user=dbConfig.user, password=dbConfig.password, dbname=dbConfig.dbName, host=dbConfig.host,port=dbConfig.port)
return dbConnection
Class:
class EmptyObject():
pass
Printed result:
('172.16.18.2',)
('5432',)
<class 'tuple'>
invalid port number: "('5432'"
invalid port number: ")"
dbConfig.host = settings.DATABASES[settingName]["HOST"],
dbConfig.port = settings.DATABASES[settingName]["PORT"],
dbConfig.user = settings.DATABASES[settingName]["USER"],
dbConfig.password = settings.DATABASES[settingName]["PASSWORD"],
Take out those commas at the end. That's the cause.
Turns out I didn't remove the commas when assigning the object variables. Remove the commas like this and it will work as expected:
def getDbPoolConfig(self):
settingName = "pool"
dbConfig = EmptyObject()
dbConfig.host = settings.DATABASES[settingName]["HOST"] # Removed commas here
dbConfig.port = settings.DATABASES[settingName]["PORT"]
dbConfig.user = settings.DATABASES[settingName]["USER"]
dbConfig.password = settings.DATABASES[settingName]["PASSWORD"]
dbConfig.dbName = settings.DATABASES[settingName]["NAME"]
return dbConfig
I'm not sure what's happening when I print my dictionary.
In Python 3, I have a dictionary of parse_blast objects called transSwiss. Each object's proteinID is the key with the entire object as the value.
I can print transSwiss in it's entirety and I can also print blasto.protein, but not when I combine them to get a dictionary value. I'm not sure what is happening when I use:
print(transSwiss[blasto.protein])
<__main__.parse_blast object at 0x000000373C5666A0>
Here is the code
class parse_blast(object):
def __init__(self, line):
#Strip end-of-line and split on tabs
self.fields = line.strip("\n").split("\t")
self.transcriptId, self.isoform = self.fields[0].split("|")
self.swissStuff = self.fields[1].split("|")
self.swissProtId = self.swissStuff[3]
self.percentId = self.fields[2]
def filterblast(self):
return float(self.percentId) > 95
class parse_matrix(object):
#Consider __init__ as a Constructor
def __init__(self, matrix_lines):
(self.protein,
self.Sp_ds,
self.Sp_hs,
self.Sp_log,
self.Sp_plat) = matrix_lines.strip("\n").split("\t")
def separate_tuples(one_tuple):
return "\t".join(one_tuple)
blastmap = map(parse_blast, blast_output.readlines())
filtered = filter(parse_blast.filterblast, blastmap)
matrixmap = map(parse_matrix, matrix_output.readlines()[1:])
transSwiss = {blasto.transcriptId:blasto for blasto in filtered}
for matrixo in matrixmap:
print(transSwiss[matrixo.protein])
Because your object is defined by you, you also need to tell python how you want it to print. You can do this by defining a function called "__str__" that returns how you want to print your object.
https://en.wikibooks.org/wiki/Python_Programming/Classes#str
I'm having hard time trying to read my dictionary variable. Python keeps throwing the following error:
TypeError: string indices must be integers
This is a sample that should give you an idea of what my problem is:
self.dict = {}
self.dict['User'] = 'User_name'
self.dict['Dir'] = 'user_home_dir'
self.dict['userID'] = 1
if self.dict['userID'] == 1: # this is the line that is said to contain an error
then do somethin ...
This is all I get as a Traceback:
user_id = self.dict['userID']
TypeError: string indices must be integers
No I'm positive that self.dict is not a string.
It's being created in a function called createUser and it's being returned to the main thread.
def createUser(self):
self.dict = {}
... user inputs information ...
... and then information is inserted into self.dict ...
self.dict['User'] = self.lineEdit_User.text()
self.dict['Dir'] = self.lineEdit_path.text()
self.dict['userID'] = int(self.lineEdit_ID.text())
return self.dict
After that self.dict is only referenced for reading data from it.
I've found the problem, and it was in my signal definition. Dictionary 'self.dict' is being returned via pyqtSignal which was defined like this:
addUser = pyqtSignal(object)
After thorough examination of my code I've figured out that I should change it to:
addUser = pyqtSignal(dict)
and once I did that it was all right. Once again, thanks everyone for their contribution.
My class gcb_ip has those attributes:
class gcb_ip:
ip = None
country_code = None
score = None
asn = None
records = list()
1) I fill up the records list with a specific method.
2) I can see the records and the rest of my attributes inside the object if I check it my main code.
3) I CAN'T see the records but the rest of my attributes inside the object if I check it into another class method passed by parameters.
I come from C++ and I guess that this is a copy/reference parameter passing issue. ¿What's going on?
Do you have your init function properly defined, and have those parameters set? For example
class gcb_ip(object):
def __init__(self, IP, country_code, score, asn):
self.IP = IP
self.country_code = country_code
self.score = score
self.asn = asn
self.records = list()
This is the equivalent of setting up your explicit constructor in C++, and initializing your member variables.
Then you can reference the parameters of that object as you would expect, for example
myIP = someGcbObject.IP
im new to python and i know there has been a lot of discussion on this but I still have a question. I am trying to access a variable from class to a same class function, its throughing a error as
"AttributeError: 'int' object has no attribute 'isOpen'"
Code is:
class serialCommunication():
ser = 0 #class global variable
def ser_port():
.....
def ser_Burdrate():
BurdRate = ( "4800",
"9600",
"19200",
"38400",
"57600",
"115200"
)
BR = int(input("Enter the Burd Rate\n0\t--\t4800\n1\t--\t9600\n2\t--\t19200\n3\t--\t38400\n4\t--\t57600\n5\t--\t115200\n\n"))
return Portno , int(BurdRate[BR]), timeout
def ser_open():
port = serialCommunication.ser_Burdrate()
serialCommunication.ser = serial.Serial(port[0], port[1], timeout=port[2])
port = serialCommunication.ser.getPort()
print (serialCommunication.ser , '\r\n')
.....
def ser_Write():
if (serialCommunication.ser.isOpen()):
print ('open: ', serialCommunication.ser.getPort())
elif (serialCommunication.ser.closed()):
serialCommunication.ser_open()
please advice on the same
thanks in advance
thanks for advice i changed
ser = serial.Serial()
and it's throughing a error as
"TypeError: 'bool' object is not callable"
in if statement the bool object can be executed right..?
You're trying to call a method .isOpen() on a int type (ser = 0 declared in the class serialCommunication) as the error suggests the object does not have this method.
I can't see the rest of the class but are you sure you shouldn't be trying to reference a method of the class directly? Also without an instance the method you call would need to be a class method prefixed with #classmethod decorator.