I am trying to pass class element to method. Element is formed dynamically inserting current time in it. Mine class looks something like this:
class MineContact(dict):
def __init__(self, **kwargs):
# set your default values
import time
curr_time = repr(time.time()).replace('.', '')
self['tel'] = [{
'type': ['Mobile'],
'value': '555%s' % curr_time[8:]}]
...
So, I create object of this class and now I want to insert it as method argument:
contact = MineContact()
extra_text = "-%d" % (self.iteration)
new_contact.insert_phone(contact.tel['value'])
When I run this script, I get this type of error:
TypeError: list indices must be integers, not str
So, does anyone knows where am I getting it wrong?
You have a list of one dictionary [{}] instead of {}. The following will work:
contact = MineContact()
extra_text = "-%d" % (self.iteration)
new_contact.insert_phone(contact.tel[0]['value'])
Alternatively, you could change your self['tel'] to a dictionary instead of a list of a dictionary. Here is what it would look like:
self['tel'] = {'type': ['Mobile'], 'value': '555%s' % curr_time[8:]}
Then, your original new_contact.insert_phone(contact.tel['value']) would work
Related
I am new to python, here is the first part of my graduation project. I want to extract data from MySql 'insert' statements
if tableName == 'accounts':
a = Account(rm_apostrophe(slippedMsgs[0]), rm_apostrophe(slippedMsgs[1]),
rm_apostrophe(slippedMsgs[2]))
print(a.account_id, a.account_name, a.customer_code)
Accounts.append(a)
In the code above, Account is a class used to save data, rm_apostrophe is a method for handle strings.
class Account:
def __init__(self, account_id, account_name, customer_code):
self.account_id = account_id
self.account_name = account_name
self.customer_code = customer_code
def rm_apostrophe(raw_data):
if raw_data is None or raw_data == "Null":
return None
elif raw_data.startswith("'"):
return raw_data[1:-1]
else:
return raw_data
Account is a simple method with only three attributes, so there is no problem with writing this way.
But I have another class named Ticket with 73 attributes, which means that I have to do rm_apostrophe(slippedMsgs[x]) 73 times in
t = Ticket(rm_apostrophe(slippedMsgs[0]), rm_apostrophe(slippedMsgs[1]),
rm_apostrophe(slippedMsgs[2])...etc)
I guess there should be an easier way to help me pass in these parameters, maybe I need to modify the constructor. Hope someone can help me, thank you very much
You can use a list comprehension to create the list of arguments:
args = [rm_apostrophe(x) for x in slippedMsgs]
Then you can pass these arguments using t = Ticket(*args)
The * before the args passes every item in the list as an argument to Ticket
I'm trying to check / return the class name exists within another class name, here is my code so far which only returns the first value in the first span '1'.
TagListPost = driver.find_elements_by_class_name("-V_eO")
for k in TagListPost:
print(k.text)
I know k.text will only return text values, I'm not sure what I need to do to return the nested class name '_1P1TY coreSpriteHeartSmall'.
I've also tried this:
PostType = driver.find_elements_by_class_name('_1P1TY coreSpriteHeartSmall')
for j in PostType:
Print(j)
I've had no luck, it doesn't return anything because it's obviously finding the class and returning the value store in the class which is null. The code above attempts to print the class handle but 'j' is empty.
Link to HTML I wish to return values from
If you want to get class attribute values of nested elements try:
TagListPost = driver.find_elements_by_class_name("-V_eO")
for k in TagListPost:
PostType = k.find_element_by_xpath('./span[#class]')
print(PostType.get_attribute('class'))
I am trying to add attributes to this class through a dictionary. I have a dictionary (dict) which follows this order
{'Subject' + str(number) : subject introduced previously}
for instance,
{'Subject0' : 'Chemistry'}
So i'm trying to implement this on a class as it follows:
class Subjects:
def __init__(self, name, dictVar, yearCourse):
self.name = name
self.dictVar = dictVar
self.yearCourse = yearCourse
self.label = self.name [0:3] + self.yearCourse
def getLabel(self):
print (self.label)
for key, value in dict.items:
key = Subjects(value, key, yearCourse)
The original code has the corresponding identation, it is a formating mistake
I took the dict.items from this question
If I run
Subject0.getLabel()
Nothing happens, since I apparently have an error in the for loop
for key, value in dict.items:
TypeError: 'builtin_function_or_method' object is not iterable
Thank you good human being if you have read this whole bible :)
I think you need to change dict.items to dict.items().
I have a code as follows:
class SifFile():
setting = {}
interesting_param = ['Temp', 'Pressure']
def __init__(self, get_param):
self.File_Type = "Andor Technology Multi-Channel File"
for k, v in get_param.items():
if SifFile.interesting_param in k:
SifFile.setting[k] = v
return SifFile.setting
get_parameter = {'Temp':75, 'Pressure':50, 'Helium':90, 'Exp':96}
sif = SifFile(get_parameter)
There is a big dict named get_parameter that has a few parameters and their values.
There is also a list named interesting_param that contains 2 elements.
What I want to do is to check which parameters from interesting_param list are present in the get_parameter dictionary and I want to save those parameters in an empty dict named setting
I tried running the above code, but it gives me the following error:
Traceback (most recent call last):
File "", line 16, in
sif = SifFile(get_parameter)
File "", line 8, in init
if SifFile.interesting_param in k:
TypeError: 'in ' requires string as left operand, not list
Expected output:
setting = {'Temp':75, 'Pressure':50}
Here is the code that will give you the expected answer:
class SifFile():
setting = {}
interesting_param = ['Temp', 'Pressure']
def __init__(self):
self.File_Type = "Andor Technology Multi-Channel File"
return
def func(self, get_param):
for k, v in get_param.items():
if k in SifFile.interesting_param:
SifFile.setting[k] = v
return SifFile.setting
get_parameter = {'Temp':75, 'Pressure':50, 'Helium':90, 'Exp':96}
sif = SifFile()
x=sif.func(get_parameter)
print(x)
I have created anothter funcion called "func" because "init()" cannot return a dictionary. It should only return "None".
Besides that, the condition statement within the for loop is changed.
The error is telling you what's wrong: you are trying to check if a key exists in a dict but the key that you're checking for isn't a string. Let's look at the line in question:
if SifFile.interesting_param in k:
The error thinks that SifFile.interesting_param is a list, so let's have a look at where you define that:
interesting_param = ['Temp', 'Pressure']
Oh yeah, that is a list. Since a list can't be a dict key it throws an error.
You need to loop through your items in interesting_param one by one to check whether they're in the dict. I've implemented that here, along with a range of other issues in your code, mainly surrounding how you'd implemented the class:
class SifFile():
"""
Class for holding and processing sif files.
"""
def __init__(self, params):
"""
Define the variables you want to use in your class
"""
self.file_type = "Andor Technology Multi-Channel File"
self.interesting_params = ['Temp', 'Pressure']
self.given_params = params
self.setting = {}
def get_settings(self):
"""
Return list of settings of interest
"""
# Look at every parameter of interest in turn
for param in self.interesting_params:
# Check to see if it is in the dict of given parameters
if param in self.given_params:
# If it is then add it to the setting dict
self.setting[param] = self.given_params[param]
# Return the setting dict once the loop is done
return self.setting
parameters = {'Temp':75, 'Pressure':50, 'Helium':90, 'Exp':96}
sif = SifFile(parameters)
print(sif.get_settings())
Note that your variables are now all instance variables rather than class variables (they start with self) because you're changing them, so they are unlikely to be the same for every class.
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.