Nov-25-2016, 09:39 PM
(Nov-25-2016, 08:33 PM)meems Wrote: I'm coming from a language that doesn't use the keywords 'self'. This 'self' example found on the net doesn't explain to me why self is necessary. In fact when I removed the 'self' the code still worked.
class Restaurant(object): bankrupt = False def open_branch(self): if not self.bankrupt: print("branch opened") x=Restaurant() x.bankrupt= True print x.bankruptclass Restaurant(object): bankrupt = False def open_branch(): if not bankrupt: print("branch opened") x=Restaurant() x.bankrupt= True print x.bankruptCode still works with self removed.
I've seen other examples where functions that are defined to take a 'self' argument, don't actually require then when called.
e.g.
class BankAccount(object): def __init__(self, initial_balance=0): self.balance = initial_balance def deposit(self, amount): self.balance += amount def withdraw(self, amount): self.balance -= amount def overdrawn(self): return self.balance < 0 my_account = BankAccount(15) my_account.withdraw(5) print my_account.balancecalling the withdraw function doesn't require any variable to fill in the 'self' parameter.
So....
Is 'self' redundant? What is the simplest code you know of where self is essential, without which the code won't work?
You code works because as you use it "bankrupt" is actually a class variable in Python. You code won't work with two distinct instances of Restaurant. You should use self.bankrupt=false to create an instance variable/attribute.
Unless noted otherwise, code in my posts should be understood as "coding suggestions", and its use may require more neurones than the two necessary for Ctrl-C/Ctrl-V.
Your one-stop place for all your GIMP needs: gimp-forum.net
Your one-stop place for all your GIMP needs: gimp-forum.net