使用 'with' returns 'None' 创建的对象
object created with 'with' returns 'None'
我正在尝试编写一个简单的银行系统。我应该提一下,我有点 Python 菜鸟。为此,我写了一篇'Account'class。
这是代码的重要部分:
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})')
当我使用
import bank
with bank.Account(1, 'name1', 500) as name1:
pass
with bank.Account(2, 'name2', 500) as name2:
pass
,代码执行没有错误,但是 'name1' 和 'name2' 都是 'None'。它们不应该是对象的引用吗?非常感谢您的帮助!
注意 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.
你没有从 __enter__
返回任何东西。 Return self
来自它:
def __enter__(self):
return self
我正在尝试编写一个简单的银行系统。我应该提一下,我有点 Python 菜鸟。为此,我写了一篇'Account'class。 这是代码的重要部分:
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})')
当我使用
import bank
with bank.Account(1, 'name1', 500) as name1:
pass
with bank.Account(2, 'name2', 500) as name2:
pass
,代码执行没有错误,但是 'name1' 和 'name2' 都是 'None'。它们不应该是对象的引用吗?非常感谢您的帮助!
注意 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.
你没有从 __enter__
返回任何东西。 Return self
来自它:
def __enter__(self):
return self