我可以访问没有初始化的类吗?Python

2024-09-28 21:32:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望能够打印模块中的“你好,哈利”。这是我的模块(称为test23):

class tool:

    def handle(self,name):
        self.name = "hello " + name

这是我的剧本:

import test23

harry= test23.tool().handle(" harry")
print harry.name

我好像不能在我的剧本里写“你好,哈利”。我该怎么做呢?你知道吗


Tags: 模块nameimportselfhellodeftoolclass
3条回答

我想这样就行了。你知道吗

from test23 import tool

harry = tool()
harry.handle("harry")
print harry.name

handle不返回任何内容,因此harry将是NoneType。 分两次执行:首先分配实例,然后调用方法:

>>> class tool:
...   def hello(self,name):
...      self.name="hello "+name
...
>>> a=tool()
>>> a.hello('i')
>>> a.name
'hello i'
>>> b=tool().hello('b')
>>> b.name
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'name'
>>> type(b)
<type 'NoneType'>

tool.handle()不返回对象,因此在调用方法之前需要存储对象:

import test23

harry = test23.tool()
harry.handle("harry")
print harry.name

相关问题 更多 >