Object has no attribute but also get global name not defined - python

I am trying my darnest to pull a variable from a text file to do some math in an trading bot algorithim.
This is my code. I have shortened it to get to the issue:
from botlog import BotLog
from botindicators import BotIndicators
from bottrade import BotTrade
class BotStrategy(object):
def __init__(self):
self.output = BotLog()
self.prices = []
self.closes = [] # Needed for Momentum Indicator
self.trades = [] #20 trades at 0.021 = .042
self.currentPrice = "" #after a day, add the BTC to 0.042 and adjust simultaneous trades
self.currentClose = "" #53 coins for 2500 simul trades per coin pair
self.numSimulTrades = 100 #looks like dash ends at 2500 trades eth ends at about 1000 trades total for all four would be about 208 coins
self.indicators = BotIndicators()
mid=0
with open('test.txt', 'r') as myfile:
mid=myfile.read().replace('\n', '')
self.output.log(mid)
mid=int(mid)
def tick(self,candlestick):
self.currentPrice = float(candlestick.priceAverage)
self.prices.append(self.currentPrice)
#self.currentClose = float(candlestick['close'])
#self.closes.append(self.currentClose)
self.output.log("Price: "+str(candlestick.priceAverage)+"\tMoving Average: "+str(self.indicators.movingAverage(self.prices,5)))
self.evaluatePositions()
self.updateOpenTrades()
self.showPositions()
def evaluatePositions(self):
openTrades = []
for trade in self.trades:
if (trade.status == "OPEN"):
openTrades.append(trade)
if (len(openTrades) < self.numSimulTrades):
if ((self.currentPrice) < self.indicators.movingAverage(self.prices,15)):
self.trades.append(BotTrade(self.currentPrice,stopLoss=.0001))
for trade in openTrades:
if ((self.currentPrice + mid) > self.indicators.movingAverage(self.prices,15)) :
trade.close(self.currentPrice)
def updateOpenTrades(self):
for trade in self.trades:
if (trade.status == "OPEN"):
trade.tick(self.currentPrice)
def showPositions(self):
for trade in self.trades:
trade.showTrade()
With "self.mid" I get the error: 'Bot1' object has no attribute 'mid'
a if I remove the "self" I get: NameError: global name 'mid' is not defined
What am I doing wrong? I'm losing my mind!
Traceback was requested: This is the No Attribute:
user#user1:~/Desktop/bot/part3$ python backtest.py
90
Price: 0.0486309 Moving Average: None
Price: 0.04853957 Moving Average: 0.048585235
Trade opened
Entry Price: 0.04853957 Status: OPEN Exit Price:
Price: 0.04847643 Moving Average: 0.0485489666667
Trade opened
Traceback (most recent call last):
File "backtest.py", line 15, in <module>
main(sys.argv[1:])
File "backtest.py", line 12, in main
strategy.tick(candlestick)
File "/home/user/Desktop/bot/part3/botstrategy.py", line 30, in tick
self.evaluatePositions()
File "/home/user/Desktop/bot/part3/botstrategy.py", line 46, in evaluatePositions
self.currentPrice= float(self.currentPrice+self.mid)
AttributeError: 'BotStrategy' object has no attribute 'mid'
And this is "mid" not defined:
user#user1:~/Desktop/bot/part3$ python backtest.py
90
Price: 0.0486309 Moving Average: None
Price: 0.04853957 Moving Average: 0.048585235
Trade opened
Entry Price: 0.04853957 Status: OPEN Exit Price:
Price: 0.04847643 Moving Average: 0.0485489666667
Trade opened
Traceback (most recent call last):
File "backtest.py", line 15, in <module>
main(sys.argv[1:])
File "backtest.py", line 12, in main
strategy.tick(candlestick)
File "/home/user/Desktop/bot/part3/botstrategy.py", line 30, in tick
self.evaluatePositions()
File "/home/user/Desktop/bot/part3/botstrategy.py", line 46, in evaluatePositions
if ((self.currentPrice + mid) > self.indicators.movingAverage(self.prices,15)) :
NameError: global name 'mid' is not defined
bottrade.py code:
from botlog import BotLog
import botstrategy
def main(argv):
currentMovingAverage = 0;
tradePlaced = False
typeOfTrade = False
dataDate = ""
orderNumber = ""
dataPoints = []
localMax = []
currentResistance = 0.018
mid = int(mid)
class BotTrade(object):
def __init__(self,currentPrice,stopLoss=0):
self.output = BotLog()
prices = []
self.status = "OPEN"
self.entryPrice = currentPrice
self.exitPrice = ""
self.output.log("Trade opened")
if (stopLoss):
self.stopLoss = currentPrice - stopLoss
def close(self,currentPrice):
self.mid = int(mid)
if currentPrice > (self.entryPrice + self.mid): #DASH likes about 0.000937, XRP about 0.000001, ETH likes 0.000855 XMR likes 0.000396
#use ETH to start with, with less than 4 trades. you get about 1.7 BTC in a week - 4 trades # 0.021=0.084 BTC. Daily is 0.24
self.status = "CLOSED"
self.exitPrice = currentPrice
self.output.log("Trade closed")
def tick(self, currentPrice):
if (self.stopLoss):
if (currentPrice < self.stopLoss):
self.close(currentPrice)
def showTrade(self):
tradeStatus = "Entry Price: "+str(self.entryPrice)+" Status: "+str(self.status)+" Exit Price: "+str(self.exitPrice)
if (self.status == "CLOSED"):
tradeStatus = tradeStatus + " Profit:! "
if (self.exitPrice > self.entryPrice):
tradeStatus = tradeStatus + " \033[92m"
else:
tradeStatus = tradeStatus + " \033[91m"
tradeStatus = tradeStatus+str(abs((self.exitPrice) - (self.entryPrice)))+" \033[0m"
self.output.log(tradeStatus)
Traceback from bottrade.py
user#user1:~/Desktop/bot/part3$ python backtest.py
Price: 1131.71486314 Moving Average: None
Price: 1103.73203402 Moving Average: 1117.72344858
Trade opened
Entry Price: 1103.73203402 Status: OPEN Exit Price:
Price: 1108.36463027 Moving Average: 1114.60384248
Trade opened
Traceback (most recent call last):
File "backtest.py", line 15, in <module>
main(sys.argv[1:])
File "backtest.py", line 12, in main
strategy.tick(candlestick)
File "/home/user/Desktop/bot/part3/botstrategy.py", line 29, in tick
self.evaluatePositions()
File "/home/user/Desktop/bot/part3/botstrategy.py", line 46, in evaluatePositions
trade.close(self.currentPrice)
File "/home/user/Desktop/bot/part3/bottrade.py", line 30, in close
self.mid = int(mid)
NameError: global name 'mid' is not defined
Full display now. Any help would be appreciated.

The run-time system is correct. In the mid case, there is no variable mid defined in evaluatePositions. Similarly, there is no object attribute mid for instances of BotStrategy. Look at the difference in your initialization:
class BotStrategy(object):
def __init__(self):
self.output = BotLog()
self.prices = []
self.closes = [] # Needed for Momentum Indicator
...
mid=int(mid)
mid is a local variable of init, not an attribute. Perhaps you need
self.mid = int(mid)
and the use self.mid when you reference that value.
Does that work for you?

Related

Internal error during connect: MLM75 instance has no attribute 'i2c'

I got an issue with this driver:
LM75_CHIP_ADDR = 0x48
LM75_I2C_SPEED = 100000
LM75_REGS = {
'TEMP' : 0x00,
'CONF' : 0x01,
'THYST' : 0x02,
'TOS' : 0x03,
'PRODID' : 0x07 # TI LM75A chips only?
}
LM75_REPORT_TIME = .8
# Temperature can be sampled at any time but the read aborts
# the current conversion. Conversion time is 300ms so make
# sure not to read too often.
LM75_MIN_REPORT_TIME = .5
class MLM75:
def __init__(self, config):
self.printer = config.get_printer()
self.name = config.get_name().split()[-1]
self.reactor = self.printer.get_reactor()
self.i2c_sen = bus.MCU_I2C_from_config(config, LM75_CHIP_ADDR,
LM75_I2C_SPEED)
self.mcu = self.i2c_sen.get_mcu()
self.report_time = config.getfloat('lm75_report_time',LM75_REPORT_TIME, minval=LM75_MIN_REPORT_TIME)
self.temp = self.min_temp = self.max_temp = 0.0
self.sample_timer = self.reactor.register_timer(self._sample_mlm75)
self.printer.add_object("mlm75 " + self.name, self)
self.printer.register_event_handler("klippy:connect",
self.handle_connect)
############# MUX HANDLER ############
self.gcode = self.printer.lookup_object('gcode')
self.mux = self.printer.load_object(config, "PCA9545A %s" % (self.name,))
self.mux.init_route = config.getint( "mux_ch", 0, minval=0, maxval=3 )
self.mux.address = config.getint( "mux_i2c_address", 112 )
self.mux.change_i2c_addr( self.mux.address )
# _mux_iic_addr = self.mux.get_info()[0]
# _mux_out_chan = self.mux.get_info()[1]
# self.gcode.respond_info('sensor: '+self.name+ '\n' +
# ' addr:'+str(_mux_iic_addr)+
# ' chan:'+str(_mux_out_chan))
self.mux_channel = 0
############# MUX HANDLER ############
def handle_connect(self):
self._init_mlm75()
self.reactor.update_timer(self.sample_timer, self.reactor.NOW)
def setup_minmax(self, min_temp, max_temp):
self.min_temp = min_temp
self.max_temp = max_temp
def setup_callback(self, cb):
self._callback = cb
def get_report_time_delta(self):
return self.report_time
def degrees_from_sample(self, x):
# The temp sample is encoded in the top 9 bits of a 16-bit
# value. Resolution is 0.5 degrees C.
return x[0] + (x[1] >> 7) * 0.5
def _init_mlm75(self):
# Check and report the chip ID but ignore errors since many
# chips don't have it
try:
prodid = self.read_register('PRODID', 1)[0]
logging.info("mlm75: Chip ID %#x" % prodid)
except:
pass
def _sample_mlm75(self, eventtime):
# self.gcode.respond_info( str(self.i) )
self.mux_channel += 1
self.mux_channel %= 4
self.mux.route( self.mux_channel ) # <<<<
# self.gcode.respond_info('mx c:'+str(self.mux.get_info()[1])) # <<<<
try:
sample = self.read_register('TEMP', 2)
self.temp = self.degrees_from_sample(sample)
except Exception:
logging.exception("mlm75: Error reading data")
self.temp = 0.0
return self.reactor.NEVER
if self.temp < self.min_temp or self.temp > self.max_temp:
self.printer.invoke_shutdown(
"MLM75 temperature %0.1f outside range of %0.1f:%.01f"
% (self.temp, self.min_temp, self.max_temp))
measured_time = self.reactor.monotonic()
self._callback(self.mcu.estimated_print_time(measured_time), self.temp)
return measured_time + self.report_time
def read_register(self, reg_name, read_len):
# read a single register
regs = [LM75_REGS[reg_name]]
params = self.i2c_sen.i2c_read(regs, read_len)
return bytearray(params['response'])
def write_register(self, reg_name, data):
if type(data) is not list:
data = [data]
reg = LM75_REGS[reg_name]
data.insert(0, reg)
self.i2c_sen.i2c_write(data)
def get_status(self, eventtime):
return {
'temperature': round(self.temp, 2),
}
def load_config(config):
# Register sensor
pheaters = config.get_printer().load_object(config, "heaters")
pheaters.add_sensor_factory("MLM75", MLM75)
This code is supposed to read, write and change the address of a MUX. For some reason I can't read part of the sensors.
That's the log:
mcu 'mcu': Starting serial connect
Loaded MCU 'mcu' 100 commands (v0.10.0-388-gd9daeb08-dirty-20220429_121230-raspberrypi / gcc: (GCC) 5.4.0 binutils: (GNU Binutils) 2.26.20160125)
MCU 'mcu' config: BUS_PINS_spi=PB3,PB2,PB1 PWM_MAX=255 CLOCK_FREQ=16000000 BUS_PINS_twi=PD0,PD1 MCU=atmega32u4 ADC_MAX=1023 STATS_SUMSQ_BASE=256
mcu 'mcu': got {u'count': 229, '#receive_time': 3173.116210849, u'sum': 315145, u'sumsq': 3550500, '#name': u'stats', '#sent_time': 3173.115847275}
Configured MCU 'mcu' (165 moves)
lm75: Chip ID 0x1e
Starting heater checks for plateHeater1
lm75: Chip ID 0x22
Starting heater checks for plateHeater2
Starting heater checks for blockHeater1
Starting heater checks for blockHeater2
mlm75: Error reading data
Traceback (most recent call last):
File "/home/heater/klipper/klippy/extras/mlm75.py", line 104, in _sample_mlm75
sample = self.read_register('TEMP', 2)
File "/home/heater/klipper/klippy/extras/mlm75.py", line 123, in read_register
params = self.i2c.i2c_read(regs, read_len) #dobaveno ot lm75.py
AttributeError: MLM75 instance has no attribute 'i2c'
mlm75: Error reading data
Traceback (most recent call last):
File "/home/heater/klipper/klippy/extras/mlm75.py", line 104, in _sample_mlm75
sample = self.read_register('TEMP', 2)
File "/home/heater/klipper/klippy/extras/mlm75.py", line 123, in read_register
params = self.i2c.i2c_read(regs, read_len) #dobaveno ot lm75.py
AttributeError: MLM75 instance has no attribute 'i2c'
I am trying to figure this thing out for 2 weeks now and my hair is starting to fall. Can someone tell me what I do wrong?
Thanks for the help

Cmd module not cooperating with *args

I am trying to develop my Binance client with the Cmd module, however when I try to call a function from another file, it gives me an error.
This is for a Binance client i am writing.
main.py
def do_order(self, *args):
"""Places an order.\n
Arguments in order:\n
Buy or Sell option.\n
Market or Limit option.\n
The crypto symbol.\n
The quantity of the order.\n
The price of the order.\n"""
market.Market.xch(*args[0], *args[1], *args[2], *args[3], *args[4])
market.py
class Market():
#l = 0
#m = 0
#b = 0
#s = 0
def xch(self, xtype1, xtype2, xsymbol, xquantity, xprice ):
print("Formulating the order...")
#Time to sort the parameters
#xtype1...
Errors
[verl#verlpc Interface]$ python main.py
Loading Accounts...
CRYPTOANAYLISIS: PREDICTOR
> order 0 0 0 0 0
Traceback (most recent call last):
File "main.py", line 99, in <module>
m.initAccounts()
File "main.py", line 92, in initAccounts
prompt.cmdloop('CRYPTOANAYLISIS: PREDICTOR')
File "/usr/lib/python3.7/cmd.py", line 138, in cmdloop
stop = self.onecmd(line)
File "/usr/lib/python3.7/cmd.py", line 217, in onecmd
return func(arg)
File "main.py", line 50, in do_order
market.Market.xch(*args[0], *args[1], *args[2], *args[3], *args[4])
IndexError: tuple index out of range
First you have to create instance of this class
m = market.Market()
And then you have use single *args
m.xch(*args)
or many arguments but without *
m.xch(args[0], args[1], args[2], args[3], args[4])
Working example
class Market():
def xch(self, xtype1, xtype2, xsymbol, xquantity, xprice ):
print("Formulating the order...", xtype1, xtype2, xsymbol, xquantity, xprice)
args = [1,2,3,4,5]
m = Market()
m.xch(*args)
EDIT: you have to use do_order(...)
with * in definiton and when you run it
def do_order(*args):
m = Market()
m.xch(*args)
args = [1,2,3,4,5]
do_order(*args)
or without * in both places
def do_order(args):
m = Market()
m.xch(*args)
args = [1,2,3,4,5]
do_order(args)

Python script error sqlite3.OperationalError: no such column:

I get this error when I run the script and I cannot see the solution. This program is supposed to draw a giveaway from a sqlite3 file which has the number of raffle tickets for a user. And recently the program the gives that creates the sqlite3 file updated some stuff (The script is made by me) and I can figure out the solution.
Traceback (most recent call last):
File "C:\Users\Admin\Desktop\Draw\Test\dave-draw.py", line 244, in <module>
dd = DaveDraw()
File "C:\Users\Admin\Desktop\Draw\Test\dave-draw.py", line 64, in __init__
self.get_viewers()
File "C:\Users\Admin\Desktop\Draw\Test\dave-draw.py", line 215, in
get_viewers
''').fetchall()
sqlite3.OperationalError: no such column: viewer_id
there's the code
#!/usr/bin/env python3
import pdb
import random
import sqlite3
class Viewer(object):
def __init__(self,
viewer_id,
twitch_name,
beam_name,
beam_id,
viewer_type,
rank,
points,
points2,
hours,
raids,
gains_currency,
gains_hours,
in_giveaways,
last_seen,
sub,
entrance_message,
entrance_message_type,
entrance_sfx
):
self.viewer_id = viewer_id
self.twitch_name = twitch_name
self.beam_name = beam_name
self.beam_id = beam_id
self.viewer_type = viewer_type
self.rank = rank
self.points = points
self.points2 = points2
self.hours = hours
self.raids = raids
self.gains_currency = gains_currency
self.gains_hours = gains_hours
self.in_giveaways = in_giveaways
self.last_seen = last_seen
self.sub = sub
self.entrance_message = entrance_message
self.entrance_message_type = entrance_message_type
self.entrance_sfx = entrance_sfx
def win_chance(self, total_tickets):
"""
Takes the total tickets (points) as a paramter and works
out the percentage chance that the viewer has of winning.
Returns the viewers win chance in percent.
"""
percent = total_tickets / 100.00
return self.points2 / percent
class DaveDraw(object):
def __init__(self):
self.debug = False
self.database_path = 'Viewers3DB.sqlite'
self.db_conn = sqlite3.connect(self.database_path)
self.get_viewers()
self.calculate_total_points()
self.assign_tickets()
def assign_tickets(self):
"""
Assigns each user a number range based on the number of
tickets they have.
e.g.
10 1-10
10 11-20
30 21-50
1 51
"""
self.tickets = {}
latest_ticket = 0
for viewer in self.viewers:
# skip anyone with no points
if viewer.points2 == 0:
continue
ticket_range_beg = latest_ticket + 1
ticket_range_end = latest_ticket + 1 + viewer.points2
latest_ticket = ticket_range_end
viewer.tickets = range(ticket_range_beg, ticket_range_end)
# assign a range of tickets:
if self.debug:
print("Assigning viewer twitch: %s beam: %s tickets %i-%i" % (viewer.twitch_name, viewer.beam_name, viewer.tickets.start, viewer.tickets.stop))
if ticket_range_beg == ticket_range_end:
if self.debug:
print("Assigning ticket {} to {}".format(ticket_range_beg, viewer.twitch_name))
self.tickets[ticket_range_beg] = viewer
next
for ticket in viewer.tickets:
if self.debug:
print("Assigning ticket {} to {}".format(ticket, viewer.twitch_name))
self.tickets[ticket] = viewer
def calculate_total_points(self):
"""
Gets the total amount of points awarded to all
viewers.
"""
self.total_points = 0
for viewer in self.viewers:
self.total_points += viewer.points2
self.total_points_percent = self.total_points / 100
print("Total points awarded (total tickets): %s" % self.total_points)
def draw(self):
"""
Picks a random number between 1 and total tickets, finds
the user that has been assigned tickets within that range and
returns the user.
"""
ticket = random.randint(1, self.total_points)
try:
winner = self.tickets[ticket]
except:
pdb.set_trace()
print("\n===== WINNER Twitch: {} / Beam: {} =====\n".format(winner.twitch_name, winner.beam_id))
print("Picked ticket {}\n".format(ticket))
print("Winner win chance: {:f}".format(winner.win_chance(self.total_points)))
print("Winner's ticket range: {}-{}".format(winner.tickets.start, winner.tickets.stop))
print("Winner's ticket amount: {}\n".format(winner.points2))
self.display_viewer(winner)
def display_random_viewer(self):
"""
Displays random viewer.
"""
self.display_viewer(self.get_random_viewer())
def display_viewer(self, viewer):
"""
Outputs the data on all viewers.
"""
print("""Viewer ID: %s\nTwitch Name: %s\nBeam Name: %s\nBeam ID: %s\nRank: %s\nPoints: %s\nPoints2: %s\nHours: %s\nRaids: %s\nGains Currency: %s\nGains Hours: %s\nInGiveaways: %s\nLastSeen: %s\nEntrance Message: %s\nEntranceMsgType: %s\nEntranceSFX: %s"""
% (
viewer.viewer_id,
viewer.twitch_name,
viewer.beam_name,
viewer.beam_id,
viewer.rank,
viewer.points,
viewer.points2,
viewer.hours,
viewer.raids,
viewer.gains_currency,
viewer.gains_hours,
viewer.in_giveaways,
viewer.last_seen,
viewer.entrance_message,
viewer.entrance_message_type,
viewer.entrance_sfx
)
)
def get_random_viewer(self):
"""
Gets a completely random viewer.
"""
return random.choice(self.viewers)
def get_viewers(self):
"""
Gets data on all the viewers in the database and stores
the data in self.viewers.
"""
c = self.db_conn.cursor()
viewers = c.execute('''
SELECT
viewer_id,
TwitchName,
BeamName,
BeamID,
Type,
Rank,
Points,
Points2,
Hours,
Raids,
GainsCurrency,
GainsHours,
InGiveaways,
LastSeen,
Sub,
EntranceMessage,
EntranceMsgType,
EntranceSFX
FROM Viewer
WHERE Type != 1
AND TwitchName NOT IN (
\'treeboydave\',
\'treebotdave\'
);
''').fetchall()
self.viewers = []
for cur_viewer in viewers:
self.viewers.append(
Viewer(
cur_viewer[0],
cur_viewer[1],
cur_viewer[2],
cur_viewer[3],
cur_viewer[4],
cur_viewer[5],
cur_viewer[6],
cur_viewer[7],
cur_viewer[8],
cur_viewer[9],
cur_viewer[10],
cur_viewer[11],
cur_viewer[12],
cur_viewer[13],
cur_viewer[14],
cur_viewer[15],
cur_viewer[16],
cur_viewer[17]
)
)
if __name__ == '__main__':
dd = DaveDraw()
dd.draw()
All your other SQL columns are capitalised, any chance that's why it's not finding the viewer_id column? Maybe it's Viewer_Id or similar?
If you sql execute 'HELP TABLE Viewer' and print what it returns, it will give you an outline of all of the columns in that database table, so you can make sure you have the capitalisation correct, or whether the column actually isn't there at all.

Not sure why I'm getting this attribute error

The assertEqual tests are from a module that just calls a function, runs some data through it, computes the result of that processed data, and compares it to my predicted answer. For example, my predicted answer for total_test was 6.0.
When I run my code (below being the troubled part), I get this error:
Traceback (most recent call last):
File "C:/Users/anon/Desktop/test.py", line 72, in <module>
TransactionTest().run()
File "C:/Users/anon/Desktop/test.py", line 68, in run
self.total_test()
File "C:/Users/anon/Desktop/test.py", line 60, in total_test
assertEqual(self.__t1.total(), 6.0)
File "C:/Users/anon/Desktop/test.py", line 18, in total
return sum(map(lambda p: p.cost(), self.__purchases))
File "C:/Users/anon/Desktop/test.py", line 18, in <lambda>
return sum(map(lambda p: p.cost(), self.__purchases))
AttributeError: 'float' object has no attribute 'cost'
All the line numbers should be shifted down a few lines to account for me copy and pasting it here very slightly modified.
Essentially, my total_test function is causing a crash when it's called. Not sure why I'm getting an attribute error.
class Transaction:
def __init__(self, purchases, tax_rate):
self.__purchases = purchases
self.__tax_rate = tax_rate
def total(self):
return sum(map(lambda p: p.cost(), self.__purchases))
def tax_rate(self):
return self.__tax_rate
def total_taxable(self):
taxable_items = filter(lambda p: p.item().taxable(),self.__purchases)
return sum(map(lambda p: p.cost(), taxable_items))
def grand_total(self):
return self.total() + self.__tax_rate * self.total_taxable()
def __str__(self):
return "Total: " + self.__total + ";" + "Total_tax: " + self.__total_taxable * self.__tax_rate + ";" + "Grand Total: " + self.__grand_total
def print_receipt(self):
f = open("receipt.txt", "w")
f.write("\n".join(map(lambda p:str(p),self.__purchases)))
f.write("\n")
f.write("Total: $%.2f" % self.total())
f.write("\n")
f.write("Tax ( $%.2f # %.2f %%): $%.2f" %(self.total_taxable(), self.__tax_rate * 100, self.__tax_rate * self.total_taxable()))
f.write("\n")
f.write("Grand Total: $%.2f" % self.grand_total())
f.close()
#problem 9-----------------------------------------------------------------------------------
class TransactionTest:
print('----------------------------')
def __init__(self):
t_list = [1.0,2.0,3.0]
self.__t1 = Transaction(t_list, 0.05)
#self.__d2 = Transaction(3.0, 0.06)
def total_test(self):
print('total_test-----------------------------------------')
assertEqual(self.__t1.total(), 6.0)
def tax_rate_test(self):
print('tax_rate_test--------------------------------------')
assertEqual(self.__t1.tax_rate(), 0.05)
#assertEqual(self.__d2.tax_rate() = Transaction(0.06))
def run(self):
self.total_test()
#self.tax_rate_test()
#self.str_test()
TransactionTest().run()
Your test code passes a list of three float instances, [1.0,2.0,3.0], as the purchases argument to Transaction's initializer. However, the other Transaction methods try to call various methods (e.g. cost() and item()) on the values from that list, and since float instances don't have the methods an exception is raised.
I suspect your Transaction code is intended to be run on a list of some other kind of object, where the appropriate methods are defined. You need to rewrite your tests to use the right kind of objects.

Python- AttributeError: 'function' object has no attribute 'course_code'

Third question for the day. But this one is a brand new program. So now I'm receiving this error (and before you say my code is riddled with errors, I'm expecting that.):
Traceback (most recent call last):
File "C:/Users/DDeahr/Downloads/College_Student.py", line 58, in <module>
main()
File "C:/Users/DDeahr/Downloads/College_Student.py", line 46, in main
Alex.complete_class("English 101", 10)
File "C:/Users/DDeahr/Downloads/College_Student.py", line 30, in complete_class
College_Student.complete_class.course_code += self.courses_done
AttributeError: 'function' object has no attribute 'course_code'
New error:
Traceback (most recent call last):
File "C:/Users/DDeahr/Downloads/College_Student.py", line 1, in <module>
class College_Student(object):
File "C:/Users/DDeahr/Downloads/College_Student.py", line 30, in College_Student
course_code = staticmethod(course_code)
NameError: name 'course_code' is not defined
Here's my code:
class College_Student(object):
total = 0
enrolled = []
def __init__(self, first_name, last_name, id_num, courses_done, credit_hrs):
self = self
self.first_name = first_name
self.last_name = last_name
self.id_num = id_num
self.courses_done = [],
self.credit_hrs = credit_hrs
def __str__(self):
first_name = self.first_name
last_name = self.last_name
id_num = self.id_num
courses_done = self.courses_done
credit_hrs = self.credit_hrs
College_Student.total += 1
College_Student.enrolled += self.last_name
College_Student.enrolled.sort()
return "First Name: %s\nLast Name: %s\nID Number: %s\nCourses Finished: %s\nCredit Hours: %s\n" % (self.first_name, self.last_name, self.id_num, self.courses_done, self.credit_hrs)
def complete_class(self,course_code,student_credit_hrs):
self.credit_hrs += student_credit_hrs
self.courses_done = []
College_Student.complete_class.course_code += self.courses_done
return "Student with ID number: %s has finished course %s which is %s credit hours." % (self.id_num, self.course_code, self.student_credit_hours)
def can_grad(self):
if self.credit_hrs >= 120:
return "Student with ID number: %s can now graduate." % (self.id_num)
else:
return "Student with ID number: %s cannot graduate yet." % (self.id_num)
def main():
print "Creating student John"
John = College_Student("John", "Appleseed", 111111, None, 20)
print John
print "Creating student Alex"
Alex = College_Student("Alex", "Trannon", 222222, None, 30)
print Alex
Alex.complete_class("English 101", 10)
Alex.complete_class("Mathmatics 102", 20)
Alex.complete_class("Computer Sciences 208", 60)
John.complete_class("Psychology 5005", 40)
John.complete_class("English 108.365", 2)
John.complete_class("Chinese 101", 10)
John.complete_class("Computer Sciences 30", 28)
Alex.can_grad()
John.can_grad()
print total
print enrolled
main()
Any and all help is much appreciated! Thank You!
If I understand what you are trying to do - change :
College_Student.complete_class.course_code += self.courses_done
to
self.courses.done.append(course_code) -
note:
self.courses.done += self.course_code
also works but as pointed out by #jonsharpe is less explicit.
Also :
in complete_class - don't set self.courses_done to [] - do that in init - where it is is at the moment it will reset the students courses list each time they complete a course
It is bad form to change the instance variables in the str method - that method should simply be used to provide a text representation of that student - as you have it coded it it seems to make changes, for no obvious reason.

Categories

Resources