Untitled
python implements class systemunknown
plain_text
a year ago
2.9 kB
5
Indexable
Never
# Let's start by defining the various functions and classes as described in the user's text. # Function to make an instance def make_instance(cls): """Return a new object instance, which is a dispatch dictionary.""" def get_value(name): if name in attributes: return attributes[name] else: value = cls['get'](name) return bind_method(value, instance) def set_value(name, value): attributes[name] = value attributes = {} instance = {'get': get_value, 'set': set_value} return instance # Function to bind a method def bind_method(value, instance): """Return a bound method if value is callable, or value otherwise.""" if callable(value): def method(*args): return value(instance, *args) return method else: return value # Function to make a class def make_class(attributes, base_class=None): """Return a new class, which is a dispatch dictionary.""" def get_value(name): if name in attributes: return attributes[name] elif base_class is not None: return base_class['get'](name) def set_value(name, value): attributes[name] = value def new(*args): return init_instance(cls, *args) cls = {'get': get_value, 'set': set_value, 'new': new} return cls # Function to initialize an instance def init_instance(cls, *args): """Return a new object with type cls, initialized with args.""" instance = make_instance(cls) init = cls['get']('__init__') if init: init(instance, *args) return instance # Create the Account class def make_account_class(): """Return the Account class, which has deposit and withdraw methods.""" interest = 0.02 def __init__(self, account_holder): self['set']('holder', account_holder) self['set']('balance', 0) def deposit(self, amount): """Increase the account balance by amount and return the new balance.""" new_balance = self['get']('balance') + amount self['set']('balance', new_balance) return self['get']('balance') def withdraw(self, amount): """Decrease the account balance by amount and return the new balance.""" balance = self['get']('balance') if amount > balance: return 'Insufficient funds' self['set']('balance', balance - amount) return self['get']('balance') return make_class(locals()) # Instantiate the Account class Account = make_account_class() # Create an account instance kirk_account = Account['new']('Kirk') # Test the account instance test_results = { 'holder': kirk_account['get']('holder'), 'interest': kirk_account['get']('interest'), 'deposit': kirk_account['get']('deposit')(20), 'withdraw': kirk_account['get']('withdraw')(5) }