I have a BankAccount class that allows a balance to be set, an amount to be deposited/withdrawn, and then a method that returns the balance.
class BankAccount():
def __init__(self, initialBalance = 0):
self.balance = initialBalance
def __repr__(self):
return("BankAccount({})".format(self.balance))
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
self.balance -= amount
def balance(self):
return(self.balance())
But when I call the balance method (b.balance()), it get a float object not callable error. But if I call it b.balance it returns the proper amount. I'm confused on what the error means and why the method call doesn't work. Thanks in advance!
It won't work to have an attribute and a method with the same name. You can either give the attribute a different name:
class BankAccount():
def __init__(self, initialBalance = 0):
self._balance = initialBalance
def __repr__(self):
return("BankAccount({})".format(self._balance))
def deposit(self, amount):
self._balance += amount
def withdraw(self, amount):
self._balance -= amount
def balance(self):
return(self._balance)
print(BankAccount())
or access the attribute directly (and remove the accessor method):
class BankAccount():
def __init__(self, initialBalance = 0):
self.balance = initialBalance
def __repr__(self):
return("BankAccount({})".format(self.balance))
def __repr__(self):
return("BankAccount({})".format(self.balance))
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
self.balance -= amount
print(BankAccount())
When you define a class, all of its methods are defined, but not called. This includes def balance(self):. Those methods are accessible via references e.g. self.methodname. When you create an instance of this class, it calls the __init__ method, defined as def __init__(self, initialBalance=0):. This method assigns an instance attribute self.balance and gives it a floating-point value. When you do that, the old instance attribute that self.balance used to point to - the method you defined - is no longer referred to, so it's collected by Python's garbage collector and disappears.
The key is that Python does not have one bag for function names and another bag for other names. It simply has a bag for all instance attribute names, whether they point to a floating-point number, a function, or something else.
Also, if you hadn't overwritten self.balance, that method would've been even more problematic, as it calls itself (recursion) with no way of stopping. So, when you call it, it will call itself, which will then call itself, forever, producing an error.
Simply remove the defined def balance(self): method entirely. It doesn't look like it was doing anything useful, and you can simply access the self.balance attribute directly.
remove
def balance(self)
it is an attribute. If you have an attribute, you don't need a method to retrieve it
self.balance() calls the balance method of the BankAccount class and b.balance is the balance attribute of the BankAccount object.
Since return is not a method you cannot do return(something) and that's why you are getting an error saying self.balance() which is a float is not callable. But when you do b.balance it is a perfectly valid syntax and it returns the value of balance attribute which is the current balance.
Suggestion: Have different names for attribute balance and method balance(probably check_balance).
Related
I have $100 cash to get some food.
Then, what is an appropriate/correct way to read/write a variable (cash) globally with different instance(apple, banana)?
#-- class definitions
class Wallet():
cash=100
class Food():
w=Wallet()
def __init__(self,price):
self.price=price
def purchase(self,num):
self.w.cash-=num*self.price
#-- instantiation
apple=Food(price=5)
banana=Food(price=10)
#-- call method
apple.purchase(num=3) #5*3=15
banana.purchase(num=4) #10*4=40
print(apple.w.cash) #100-(15+40)=45
print(banana.w.cash) #100-(15+40)=45
This looks correct, but I feel uncomfortable because this code overwrites cash, which is defined as a class variable in Wallet class. (Class variables should not be overwritten, from my understanding.)
Would it be better not to define Wallet class but to define cash as a global variable?
If I insist on defining Wallet class, how should cash be treated in instantiated classes?
Maybe you meant static class variables shouldn't be overwritten.
Also I'm not sure why food has a purchase method. Perhaps you can create another class such as Customer, then have Wallet be a class variable of Customer.
You can do something like:
class Wallet:
def __init__(self, cash):
self.cash = cash
def add_cash(self, amount):
self.cash += amount
def subtract_cash(self, amount):
self.cash -= amount
class Customer:
def __init__(self, wallet):
self.wallet = wallet
def purchase(self, food):
self.wallet.subtract_cash(food.value)
class Food:
def __init__(self, value):
self.value = value
So I wrote a code with a Bank class that has a validation method and a SavingAccount class that has a withdraw method, and I'm trying to use aggregation to associate them both, but it isn't working. The validation is validating everything. The focus should be in the Bank class and the SavingAccount class and at the end I put the instance that shouldn't work (acc1.withdraw()), I put the others class so that you can try out the code, anyway here is the code :
Expected behavior: Without calling the add_acc() function, the validation should return False and it shouldn't let me use the withdraw() function.
Actual behavior: I'm able to withdraw() even when the add_acc() wasn't called
from abc import ABC, abstractmethod
class Account(ABC):
def __init__(self, agency, acc_number, balance):
self.agency = agency
self.acc_number = acc_number
self.balance = balance
#abstractmethod
def withdraw(self, value):
pass
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
class Bank:
def __init__(self):
self.account = {}
def add_acc(self, client, account):
self.account.update({f'{client}': account})
def validation(self):
if self.account:
for acc in self.account:
if acc in self.account:
return True
else:
return False
class SavingAccount(Account):
if Bank.validation:
def withdraw(self, value):
if self.balance < value:
print('Insufficient funds.')
return
self.balance -= value
print(f'{value} dollars withdrawn. Current balance: {self.balance}$')
else:
print('Account information invalid.')
class Client(Person):
def __init__(self, name, age, acc_type):
super().__init__(name, age)
self.acc_type = acc_type
bank1 = Bank()
acc1 = SavingAccount(33333, 33330, 2000)
client1 = Client('Matthew', 40, acc1)
acc1.withdraw(500) # Right here this shouldn't work without me adding bank1.add_acc()
There are two major issues with your code.
The first is that your implementation of SavingsAccount is seriously flawed. You're checking if Bank.validate is truthy, rather than calling it. But even if you did call it, it wouldn't make any sense at the location you have the call. You are attempting to do the validation when the class is defined, not when you create an instance of the class, or try to withdraw funds. That doesn't make any sense. The concept of savings accounts (i.e. the definition of the class) should be able exist even if there haven't been any banks founded yet. Do the validation some time later! And probably you need to be validating with some specific instance of the Bank class, not with the Bank class directly.
The second issue is that your Bank.validate method doesn't do anything useful. It loops over all the keys in the self.accounts dictionary, but then just checks the first one to see if it's in the dictionary (which is always will be, if you reached that part of the code), and then returns. Probably you want that function to be checking one specific account, not checking in general for arbitrary accounts. That account (or an account number, or something) should probably be an argument to the function.
so for this piece of code, the program has to instantiate the object "acc1" where acc1 = BankAccount(1000), where 1000 is the balance. Using the class definition for Bank Account, and using a display method, acc1.display(), the code should print "balance=1000". My code is printing the balance is part, but not taking into account the 1000 part.
class BankAccount:
def __init__ (self,balance):
self.balance = balance
acc1 = BankAccount("1000")
acc1.display()
print("Balance=",acc1,sep="")
You are trying to print the object itself rather than its balance. You will get the default value printed for the BankAccount class (something like <__main__.BankAccount object at 0x7f2e4aff3978>).
There are several ways to resolve the issue:-
First print just the balance property
print("balance=",acc1.balance,sep="")
If you want to modify the class you can define the display method. This isn't ideal as it limits the way the display information can be used. It has to be displayed to standard out, it cant be joined to other strings etc. It is less flexible.
It would be better to define __str__ and return the display string which can be displayed, concatenate etc.
class BankAccount:
def __init__ (self,balance):
self.balance = balance
def display(self):
print('balance=%s' % self.balance)
def __str__(self):
return 'balance=%s' % self.balance
acc1 = BankAccount("1000")
acc1.display() # use display
print(acc1) # use __str__
I want to change the name of the object each time a object is created so that there's an accumulator adding everytime an object is created. In this example i want the first object.name to be B1 and then the second object.name to be B2 and then B3 and so on. This is what im trying to get
class Object:
def __init__(self):
self.name = "B" + (accumulator)
this is what I tried but i am not really getting anywhere
class BankAccount:
def __init__(self, balance):
self.account_number = "B" + str(number = number + 1)
self.balance = balance
I cant think of a way to avoid the issue of trying to set a variable to equal plus one of itself because itself isn't defined yet.
The simplest approach here is a class variable that stores the next value to use, which you increment after use:
class BankAccount:
_nextnum = 1
def __init__(self, balance):
self.account_number = "B" + str(self._nextnum)
type(self)._nextnum += 1 # Must set it on the class, or you only make a shadowing instance attribute
self.balance = balance
This isn't thread safe without locking though, so if you want thread-safety, itertools.count can do the same job in a thread-safe (at least on CPython) manner:
import itertools
class BankAccount:
_numgenerator = itertools.count(1)
def __init__(self, balance):
self.account_number = "B" + str(next(self._numgenerator))
self.balance = balance
Since itertools.count's work is done at the C layer with the GIL held, it operates atomically, both returning the next number and moving the count along as a single atomic operation.
You can have a class level variable maintain how many objects were created, and then use that to determine the name
class BankAccount:
count = 0
def __init__(self):
self.name = "B" + str(BankAccount.count)
BankAccount.count += 1
This is not thread safe however, as mentioned by #ShadowRanger. It's likly a better idea to use itertools.count as they suggest.
In Python, how do you make a subclass from a superclass?
# Initialize using Parent
#
class MySubClass(MySuperClass):
def __init__(self):
MySuperClass.__init__(self)
Or, even better, the use of Python's built-in function, super() (see the Python 2/Python 3 documentation for it) may be a slightly better method of calling the parent for initialization:
# Better initialize using Parent (less redundant).
#
class MySubClassBetter(MySuperClass):
def __init__(self):
super(MySubClassBetter, self).__init__()
Or, same exact thing as just above, except using the zero argument form of super(), which only works inside a class definition:
class MySubClassBetter(MySuperClass):
def __init__(self):
super().__init__()
A heroic little example:
class SuperHero(object): #superclass, inherits from default object
def getName(self):
raise NotImplementedError #you want to override this on the child classes
class SuperMan(SuperHero): #subclass, inherits from SuperHero
def getName(self):
return "Clark Kent"
class SuperManII(SuperHero): #another subclass
def getName(self):
return "Clark Kent, Jr."
if __name__ == "__main__":
sm = SuperMan()
print(sm.getName())
sm2 = SuperManII()
print(sm2.getName())
class MySubClass(MySuperClass):
def __init__(self):
MySuperClass.__init__(self)
# <the rest of your custom initialization code goes here>
The section on inheritance in the python documentation explains it in more detail
class Class1(object):
pass
class Class2(Class1):
pass
Class2 is a sub-class of Class1
In the answers above, the super is initialized without any (keyword) arguments. Often, however, you would like to do that, as well as pass on some 'custom' arguments of your own. Here is an example which illustrates this use case:
class SortedList(list):
def __init__(self, *args, reverse=False, **kwargs):
super().__init__(*args, **kwargs) # Initialize the super class
self.reverse = reverse
self.sort(reverse=self.reverse) # Do additional things with the custom keyword arguments
This is a subclass of list which, when initialized, immediately sorts itself in the direction specified by the reverse keyword argument, as the following tests illustrate:
import pytest
def test_1():
assert SortedList([5, 2, 3]) == [2, 3, 5]
def test_2():
SortedList([5, 2, 3], reverse=True) == [5, 3, 2]
def test_3():
with pytest.raises(TypeError):
sorted_list = SortedList([5, 2, 3], True) # This doesn't work because 'reverse' must be passed as a keyword argument
if __name__ == "__main__":
pytest.main([__file__])
Thanks to the passing on of *args to super, the list can be initialized and populated with items instead of only being empty. (Note that reverse is a keyword-only argument in accordance with PEP 3102).
There is another way to make subclasses in python dynamically with a function type():
SubClass = type('SubClass', (BaseClass,), {'set_x': set_x}) # Methods can be set, including __init__()
You usually want to use this method when working with metaclasses. When you want to do some lower level automations, that alters way how python creates class. Most likely you will not ever need to do it in this way, but when you do, than you already will know what you are doing.
class Subclass (SuperClass):
# Subclass stuff here
You use:
class DerivedClassName(BaseClassName):
For details, see the Python docs, section 9.5.
class Mammal(object):
#mammal stuff
class Dog(Mammal):
#doggie stuff
Subclassing in Python is done as follows:
class WindowElement:
def print(self):
pass
class Button(WindowElement):
def print(self):
pass
Here is a tutorial about Python that also contains classes and subclasses.
class BankAccount:
def __init__(self, balance=0):
self.balance = int(balance)
def checkBalance(self): ## Checking opening balance....
return self.balance
def deposit(self, deposit_amount=1000): ## takes in cash deposit amount and updates the balance accordingly.
self.deposit_amount = deposit_amount
self.balance += deposit_amount
return self.balance
def withdraw(self, withdraw_amount=500): ## takes in cash withdrawal amount and updates the balance accordingly
if self.balance < withdraw_amount: ## if amount is greater than balance return `"invalid transaction"`
return 'invalid transaction'
else:
self.balance -= withdraw_amount
return self.balance
class MinimumBalanceAccount(BankAccount): #subclass MinimumBalanceAccount of the BankAccount class
def __init__(self,balance=0, minimum_balance=500):
BankAccount.__init__(self, balance=0)
self.minimum_balance = minimum_balance
self.balance = balance - minimum_balance
#print "Subclass MinimumBalanceAccount of the BankAccount class created!"
def MinimumBalance(self):
return self.minimum_balance
c = BankAccount()
print(c.deposit(50))
print(c.withdraw(10))
b = MinimumBalanceAccount(100, 50)
print(b.deposit(50))
print(b.withdraw(10))
print(b.MinimumBalance())
this is a small code:
# create a parent class
class Person(object):
def __init__(self):
pass
def getclass(self):
return 'I am a Person'
# create two subclass from Parent_class
class Student(Person):
def __init__(self):
super(Student, self).__init__()
def getclass(self):
return 'I am a student'
class Teacher(Person):
def __init__(self):
super(Teacher, self).__init__()
def getclass(self):
return 'I am a teacher'
person1 = Person()
print(person1.getclass())
student1 = Student()
print(student1.getclass())
teacher1 = Teacher()
print(teacher1.getclass())
show result:
I am a Person
I am a student
I am a teacher
A minor addition to #thompsongunner's answer.
To pass args to your superclass (parent), just use the function signature of the parent class:
class MySubClassBetter(MySuperClass):
def __init__(self, someArg, someKwarg="someKwarg"):
super().__init__(someArg, someKwarg=someKwarg)
You are calling the parent's __init__() method as if you are constructing any other class which is why you don't need to include self.