我可以在没有__init__的情况下访问课程吗? - Python

时间:2017-03-31 14:53:42

标签: python function class

我希望能够从模块中打印“hello harry”。这是我的模块(称为test23):

class tool:

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

这是我的剧本:

import test23

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

我似乎无法在我的脚本闲置中打印“你好哈利”。我该怎么做呢?

4 个答案:

答案 0 :(得分:3)

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'>

答案 1 :(得分:3)

我认为这样做会。

from test23 import tool

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

答案 2 :(得分:1)

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

import test23

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

答案 3 :(得分:1)

您想要做的是:

harry = test23.tool()  # Ok harry is a tool object
harry.handle(" harry") # Ok harry.name has been set to " harry"
print harry.name       # Ok print successfully "hello  harry"

但你做的是:harry= test23.tool().handle(" harry")

让我们一次看一遍:

  • test23.tool():构建一个新的(临时)tool对象
  • test23.tool().handle(" harry"):设置临时属性name并返回... None
  • harry= test23.tool().handle(" harry"):设置临时tool对象的属性名称,将harry设置为handle方法的返回值None =&gt ;与harry = None
  • 相同

或者,您应该更改handle以返回tool对象:

班级工具:

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