I have a small project and I have been unable to get the following statement to work. Any help would be great. User inputs can either self.sale_head which is a $ value,if a $ value is not add a self.estimated_weight_hd is used to get the total weight, the code below should return a estimated_weight_total which can be used for the total sale price. All works when I add the estimated_weight_total manually. I am lost as why.
def calc_estimated_weight_total(self):
if self.sale_head <= 0:
amount = (self.number * self.estimated_weight_hd)
return amount
def save(self):
self.estimated_total_weight = self.calc_estimated_weight_total()
super(SaleNote, self).save()
Your code doesn't do what you want cause if self.sale_head > 0 nothing will return. From your description, I think your code should be somthing like:
def calc_estimated_weight_total(self):
if self.sale_head <= 0:
amount = (self.number * self.estimated_weight_hd)
return amount
else:
return something_only_you_know
def save(self):
self.estimated_total_weight = self.calc_estimated_weight_total()
super(SaleNote, self).save()
Related
I am new to Python and trying to make a function for an assignment that will transfer money from a checking to a savings account,. We were given this initial code:
class portfolio:
def __init__(self):
self.checking = {}
self.saving = {}
self.credit = {}
self.stock = {}
And then the start of this code to make the function to transfer the money:
def invest_in_savings_account(self, account_id_savings, amount, account_id_checking):
I've tried numerous code, but none will pass the test cases. Can someone explain to me why this won't work?
def invest_in_savings_account(self, account_id_savings, amount, account_id_checking):
try:
self.checking[account_id_checking] -= amount
self.saving[account_id_savings] += amount
except:
return None
If the account id doesn't exist or if there are no funds in the checking account, the function is to do nothing.
Any suggestions would be greatly appreciated! I've worked on this all day and haven't been able to solve it.
This is the test case it must pass:
myportfolio.invest_in_savings_account('discover_saving_3785', 1000, 'discover_7732')
if (myportfolio.saving == {'chase_saving_4444': 0, 'discover_saving_3785':1000}) and (myportfolio.checking == {'chase_6688': 100, 'discover_7732':5500}):
print('Pass')
else:
print('Fail')
There are a few things going on here, most simple first, always start a class with a capital letter, it isn't necessary but it's good practice:
def class Portfolio:
After reading your comments it appears you need this to work without money in the accounts. You can write the code but you won't be able to test it, so really you need to make functions to create accounts and to add / remove money. If you haven't created any accounts your dictionaries will always come back empty. If you don't put money into them then the function will never do anything, I'm confused as to how you would go about moving something that doesn't exist.
Try something like this:
def create_checking_account(self,account_id):
self.checking[account_id] = None
def add_funds_checking(self,account_id,amount):
self.checking[account_id] += amount
def invest_in_savings(self, account_id_savings, amount, account_id_checking):
if self.checking[account_id_checking] >= amount:
self.checking[account_id_checking] -= amount
self.savings[account_id_savings] += amount
else:
print('error')
field declaration
price=fields.Integer(string="Price")
service_date=fields.Date(string="Last servicing date")
service_charge=fields.Integer(string="Last Service Charge")
total_charge=fields.Integer(string="Total Spent")
onchange Function in which servie_date is used as argument
#api.onchange('service_date')
def _onchange_total_charge(self):
if self.total_charge > 0:
self.total_charge+=self.service_charge
else:
self.total_charge=self.price+self.service_charge
#api.onchange('service_date')
#api.depends('service_date')
def _onchange_total_charge(self):
if self.total_charge > 0:
self.total_charge += self.service_charge
else:
self.total_charge = self.price + self.service_charge
Try to re-write the code like this
I've used your code it works on my odoo instance. Please make sure that you call the same in field in your xml file. you can also use compute field to get your calculation done.
I'm coding a shopping cart class to implement a shopping cart that i often find on
websites where i can purchase some goods.Im thinking about stuff that i can store in a cart and also operations that i can perform on the cart. To
simplify matters, i consider the website to be an electronics e-store that
has goods like flat-panel TVs, boomboxes, iPods, camcorders, and so on. Here is my final code
class ShoppingCart(object):
def __init__(self, s_name = ""):
self.s_items = []
self.s_total = 0
self.s_shopper = s_name
self.s_address = ""
def add_item(self, s_T):
self.s_items.append(s_T)
self.s_total = sum([s_t[2]for s_t in self.s_items])
def print_cart(self):
print("\n Shipping:",self.s_address)
print("\n Cart:")
print("Name, \t\t ID, quantity, price")
for s_t in self.s_items:
print(s_t[0],"\t",s_t[3],"\t",s_t[1],"\t",s_t[2])
print("\n Total:", self.s_total)
def set_address(self,a):
self.s_address = a
def get_address(self):
return self.s_address
def demo(self):
R = ShoppingCart('Karlson')
R.add_item(('boom', 1, 23, 123))
R.add_item(('baam', 2, 130, 242))
R.set_address('123 main, smweher, MN')
R.print_cart()
When i run the code, nothing happens and i got "Processed finished with exit code 0" Usually, when my code isnt working, i got syntax or indentation errors and being a noob in coding that got downvotes in here for 0 reason, i dont know if that error only happens in my machine or is it related to the code?
You need to write some code at module scope to actually use your class. Looking at your code, you probably want something like this:
if __name__ == '__main__':
cart = ShoppingCart()
cart.demo()
There are quite a few other questions here around this but none of them have helped.
I would like a yield field to be calculated by yield = starts / finishes fields. I'd like to graph it using Highcharts.
However when I add an object via Admin portal - it's setting yield = 0 and won't calculate.
models.py:
class wYield(models.Model):
starts = models.PositiveIntegerField(default=0)
finishes = models.PositiveIntegerField(default=0)
## ONE: i've tried the below:
yield_num = model.FloatField()
def save(self, *args, **kwargs):
if self.starts > 0:
self.yield = self.finishes / self.starts
else:
self.yield = 0
super(wYield, self).save(*args, **kwargs)
## TWO: i've tried this but then I don't know how to see it in the Admin view:
def _set_yield(self):
if self.starts > 0:
x = self.finishes / self.starts
else:
x = 0
return x
yield_num = property(_set_yield)
## THREE: I think this works the same as TWO
#property
def yield_num(self):
if self.starts > 0:
return self.finishes / self.starts
else:
return 0
admin.py:
from .models import wYield
class wYieldAdmin(admin.ModelAdmin):
list_display = ('starts', 'finishes', 'yield_num')
admin.site.register(wYield, wYieldAdmin)
Figured it out (w the help of AbhiP!) Python int typecasting was the main culprit. Stupid problem to have!
Below is what worked, and allowed me to not save the calculated field (but display it and make it act like a field in the model):
#property
def yield_num(self):
if self.starts > 0:
#needed the float() to cast it out of an int
return self.finishes / float(self.starts)
else:
return 0
Maybe you don't have to save it on the db every time as it can be calculated on the fly; otherwise you'd be wasting space. Not to mention duplicity in the db values.
Also, if tomorrow your logic changes for yield you will have full freedom to do it on to your lambda expressions. Here's one example:
Class wYieldAdmin(admin.ModelAdmin):
yield = lambda self: (self.finishes / self.starts) if self.starts > 0 else 0
yield.short_description = 'Yield'
list_display = ('starts', 'finishes', 'yield')
Class wYieldAdmin(admin.ModelAdmin):
yield = lambda self: (self.finishes / self.starts) if self.starts > 0 else 0
yield.short_description = 'You have a big head'
list_display = ('starts', 'finishes', 'yield')
This question already exists:
Closed 11 years ago.
Possible Duplicate:
Fundamentals of Python Chapter 8 project 3
Hi I am a newbie programmer who just started to learn about python.
I have recently posted this same question before and I have solved it but my answer is not exactly what the question is asking.
I need help on why I need to implement a new method even though I could do the other way.
thanks
Question:
The __str__ method of the Bank class returns a string containing the
accounts in random order. Design and implement a change that causes
the accounts to be placed in the string by order of name.
[this is the part where I don't understand]
(Hint: You will also have to define a new method in the SavingsAccount class.)
class Bank(object):
def __init__(self):
self._accounts = {}
def __str__(self):
"""Return the string rep of the entire bank."""
pTemp =[]
for i in xrange(len(SavingsAccount.temp)-1):
if self._accounts.get(SavingsAccount.temp[i]).getName() >= self._accounts.get(SavingsAccount.temp[i+1]).getName():
temp = SavingsAccount.temp[i]
SavingsAccount.temp[i] = SavingsAccount.temp[i+1]
SavingsAccount.temp[i+1] = temp
for i in SavingsAccount.temp:
pTemp.append(self._accounts[i])
return '\n'.join(map(str, pTemp))
def add(self, account):
"""Inserts an account using its PIN as a key."""
self._accounts[account.getPin()] = account
def remove(self, pin):
return self._accounts.pop(pin, None)
def get(self, pin):
return self._accounts.get(pin, None)
def computeInterest(self):
"""Computes interest for each account and
returns the total."""
total = 0.0
for account in self._accounts.values():
total += account.computeInterest()
return total
class SavingsAccount(object):
"""This class represents a Savings account
with the owner's name, PIN, and balance."""
RATE = 0.02
temp = []
def __init__(self, name, pin, balance = 0.0):
self._name = name
self._pin = pin
self._balance = balance
SavingsAccount.temp.append(self)
def __str__(self):
result = 'Name: ' + self._name + '\n'
result += 'PIN: ' + self._pin + '\n'
result += 'Balance: ' + str(self._balance)
return result
def getBalance(self):
return self._balance
def getName(self):
return self._name
def getPin(self):
return self._pin
def deposit(self, amount):
"""Deposits the given amount and returns the
new balance."""
self._balance += amount
return self._balance
def withdraw(self, amount):
"""Withdraws the given amount.
Returns None if successful, or an
error message if unsuccessful."""
if amount < 0:
return 'Amount must be >= 0'
elif self._balance < amount:
return 'Insufficient funds'
else:
self._balance -= amount
return None
def computeInterest(self):
"""Computes, deposits, and returns the interest."""
interest = self._balance * SavingsAccount.RATE
self.deposit(interest)
def main():
bank = Bank()
bank.add(SavingsAccount("Zelda","1003",5000.00))
bank.add(SavingsAccount("Wilma","1001",4000.00))
bank.add(SavingsAccount("Fred","1002",1000.00))
print bank
main()
I think the question expects you to define ordering in the SavingsAccount class, that is, be able to determine whether an instance of SavingAccounts comes after or before another instance of SavingAccount. I don't want to write any spoiler here, but tell me if my hint is not enough ;).
UPDATE
Also, a common source of errors in Python with string ordering : a comes before z which comes before A which comes before Z ...
UPDATE2
more hints ;)
What you really want here is to sort a list of instances of SavingAccount according to a given criteria. There are 2 way to do this kind of thing. You can either :
have the one doing the sorting take care of it
or you can have the instances stored in your list taking care of it.
The second option is usually better because "the class to be sorted" should know better than anybody else how to sort itself (it's about encapsulation : not letting people outside control how your class works). Even though the question is not really clear, and the example is not very good (in my opinion), this is the option they would like you to chose.
The idea is that the Bank should just do something like this :
class Bank(object):
def __str__(self):
"""Return the string rep of the entire bank."""
#get a sorted copy of the list
#using default SavingAccount comparison
pTemp =sorted(self._accounts)
return '\n'.join(map(str, pTemp))
And SavingAccount contains information about how to sort.
You may want to have a look at this article from the PythonInfo Wiki.
Also: http://docs.python.org/reference/datamodel.html#object.__lt__