Reputation: 23
When I try to access the class instance using the name generated by a for loop I am getting
"AttributeError: 'str' object has no attribute".
I am new to Python and please excuse any "Not the best practice". Any help is appreciated
class Csv:
def __init__(self, invoicenum, customer, invoicedate, duedate, description, amount, productservice, invoiceclass):
self.invoicenum = invoicenum
self.customer = customer
self.invoicedate = invoicedate
self.duedate = duedate
self.description = description
self.amount = amount
self.productservice = productservice
self.invoiceclass = invoiceclass
self.line = '{},{},{},{},{},{},{},{}\n'.format(invoicenum, customer, invoicedate,
duedate, description, amount, productservice, invoiceclass)
def wite_to_db(self):
mydb = mysql.connector.connect(host="localhost", user="root",
passwd="passwd", database="invoice")
mycursor = mydb.cursor()
sql = "insert into invoice " "(Invoice_no, Customer, Invoice_Date, Due_date, Description, Amount, Product_service, Class)" "VALUES (%s,%s,%s,%s,%s,%s,%s,%s)"
val = (self.invoicenum, self.customer, self.invoicedate, self.duedate,
self.description, self.amount, self.productservice, self.invoiceclass)
mycursor.execute(sql, val)
mydb.commit()
x0 = Csv("1355", "Test1 User", "2020-05-03", "2020-12-31", 7095, 300, "Tithe", "General Fund")
x1 = Csv("1124", "Test2 User", "2020-05-03", "2020-12-31", 7095, 300, "Tithe", "General Fund")
x2 = Csv("14432", "Test3 User", "2020-05-03", "2020-12-31", 7095, 300, "Tithe", "General Fund")
x3 = Csv("1312", "Test4 User", "2020-05-03", "2020-12-31", 7095, 300, "Tithe", "General Fund")
line_range = range(4)
for line in line_range:
line_instance = 'x' + str(line)
print(line_instance)
line_instance.write_to_db()
Upvotes: 1
Views: 1517
Reputation: 23
I assigned the class instances to a list and was able to call the method for the instances looping over it. All ya' are awesome.
Upvotes: 1
Reputation: 6944
What you've done is when you created the line_instance
variable, you made it a string, and then a couple lines later you essentially tried to run the function in your Csv class - write_to_db
on a string. That's why the error is occuring.
What I can recommend doing is something as follows:
x0 = Csv(...
x1 = Csv(...
x2 = Csv(...
x3 = Csv(...
x_list = [x0, x1, x2, x3]
for x in x_list:
x.write_to_db()
wite_to_db
" function in your Csv classUpvotes: 1
Reputation: 12927
line_instance = 'x' + str(line)
print(line_instance)
line_instance.write_to_db()
This is wrong. Strings do not have write_to_db
method. You defined this method (or rather a very similarly named wite_to_db
…) in your Csv
class, but line_instance
obviously is a string here, not an instance of Csv
class. What you probably wanted to do is:
for line_instance in (x0, x1, x2, x3):
line_instance.write_to_db()
Upvotes: 2