Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
is 'self' optional ?
#3
(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.bankrupt
class Restaurant(object):
    bankrupt = False
    def open_branch():
        if not bankrupt:
            print("branch opened")

x=Restaurant()
x.bankrupt= True
print x.bankrupt
Code 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.balance
calling 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
Reply


Messages In This Thread
is 'self' optional ? - by meems - Nov-25-2016, 08:33 PM
RE: is 'self' optional ? - by metulburr - Nov-25-2016, 09:36 PM
RE: is 'self' optional ? - by Ofnuts - Nov-25-2016, 09:39 PM
RE: is 'self' optional ? - by meems - Nov-26-2016, 12:45 AM
RE: is 'self' optional ? - by metulburr - Nov-26-2016, 02:13 AM
RE: is 'self' optional ? - by nilamo - Dec-06-2016, 08:11 PM
RE: is 'self' optional ? - by metulburr - Dec-06-2016, 08:53 PM
RE: is 'self' optional ? - by nilamo - Dec-06-2016, 10:26 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  using mutable in function defintion as optional paramter akbarza 8 522 Apr-27-2024, 09:59 PM
Last Post: snippsat
  Trouble making an argument optional linuxnoob 2 2,952 Aug-31-2018, 01:52 AM
Last Post: linuxnoob

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020