semiflex
semiflex

Reputation: 1246

Can I access a class without an __init__? - Python

I want to be able to print "hello harry" from a module. This is my module (called test23):

class tool:

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

This is my script:

import test23

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

I can't seem to print "hello harry" inside my script idle. How would I go about doing this?

Upvotes: 0

Views: 133

Answers (4)

Serge Ballesta
Serge Ballesta

Reputation: 149125

What you wanted to do is:

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"

But what you did is: harry= test23.tool().handle(" harry")

Let's look one pass at a time:

  • test23.tool() : builds a new (temporary) tool object
  • test23.tool().handle(" harry") : sets the attribute name of the temporary and returns... None!
  • harry= test23.tool().handle(" harry") : sets the attribute name of a temporary tool object, set harry to the return value of the handle method which is None => same as harry = None

Alternatively, you should change handle to return the tool object:

class tool:

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

Upvotes: 1

Aaron Brock
Aaron Brock

Reputation: 4536

tool.handle() doesn't return an object, so you need to store the object before you call the method:

import test23

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

Upvotes: 1

Will Elson
Will Elson

Reputation: 341

I think this will do it.

from test23 import tool

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

Upvotes: 3

fredtantini
fredtantini

Reputation: 16566

handle doesn't return anything, so harry will be NoneType. Do it in two times: first assign the instance, then call the method:

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

Upvotes: 3

Related Questions