Simon Oberer
Simon Oberer

Reputation: 3

object created with 'with' returns 'None'

I'm trying to program a simple bank system. I should mention that I am a bit of a Python noob. For this, I have written an 'Account' class. This is the important part of the code:

class Account:
    def __init__(self, _key, name, money):
        self.key = _key
        self.name = name
        self.money = money
        self.listhistory = [['start',
                             self.money,
                             datetime.datetime.now()
                             ]]

    def __enter__(self):
        pass

    def __exit__(self, exc_type, exc_value, exc_tb):
        pass

    def __str__(self):
        return str(self.key)

    def __repr__(self):
        return (f'{self.__class__.__name__}('
                f'{self.key},'
                f'{self.name},'
                f'{self.money})')

When I use

import bank


with bank.Account(1, 'name1', 500) as name1:

    pass

with bank.Account(2, 'name2', 500) as name2:
    pass

, the code executes without an Error, but 'name1' and 'name2' are both 'None'. Shouldn't they be references of the object? I would really appreciate some help!

Upvotes: 0

Views: 176

Answers (1)

Carcigenicate
Carcigenicate

Reputation: 45781

Note the documentation for __enter__:

The with statement will bind this method’s return value to the target(s) specified in the as clause of the statement, if any.

You aren't returning anything though from __enter__. Return self from it:

def __enter__(self):
    return self

Upvotes: 3

Related Questions