Need help on a project To :"Create a class called BankAccount with the following parameters "

Steven D'Aprano steve at pearwood.info
Sat Dec 12 07:32:39 EST 2015


On Sat, 12 Dec 2015 08:05 pm, Harbey Leke wrote:

> Create a class called BankAccount


class BankAccount:
    pass


That's easy. Unfortunately, that class does nothing, but at least it exists!
Now all you have to do is create *methods* of the class that do the work.

Here I give it a method called "display_balance" which prints the balance of
the account:

class BankAccount:
    def display_balance(self):
        bal = self.balance
        print(bal)


Notice that the method is indented inside the class.

Unfortunately, that method doesn't work yet. The problem is, the account
doesn't yet have a balance, so obviously trying to print it will fail.
First you need to do the next part of the assignment:


> .Create a constructor that takes in an integer and assigns this to a
> `balance` property.

A "constructor" is a special method that Python automatically used to create
new instances. (I hope you understand what instances are!) Python classes
have two constructor methods:

    __new__

    __init__

Notice that they both start and end with TWO underscores.

Chances are, you won't need to use __new__, you will probably use __init__
instead. (Technically, __init__ is an initializer method, not a
constructor, but most people don't care about the difference.) So you have
to write a method called "__init__" that takes an integer argument (don't
forget the "self" argument as well!) and assigns that to a balance
property.


Here is how you assign a value to a attribute called "name":

    self.name = "Harbey"


And an attribute called "number":

    self.number = 23


And an attribute called "address":


    self.address = "742 Evergreen Terrace Springfield"


See the pattern? How would you assign to an attribute called "balance"? Put
that *inside* the constructor method inside the class.



> .Create a method called `deposit` that takes in cash deposit amount and
> updates the balance accordingly.
> 
> .Create a method called `withdraw` that takes in cash withdrawal amount
> and updates the balance accordingly. if amount is greater than balance
> return `"invalid transaction"`


Again, you need to create two new methods. Remember, you create a method
with "def ..." and indent it inside the class. They must have a "self"
argument, plus whatever extra arguments the instructions above demand.

Here is how you would triple an attribute called "total":


    self.total = 3 * self.total


How would you add or subtract from "balance" instead?


I've given you most of the pieces you need to solve this problem. You just
need to assemble them into working code. Off you go, write some code, and
if you have any problems, show us what code you have written and ask for
help. Just don't ask us to do your assignment for you.




-- 
Steven




More information about the Python-list mailing list