Jeff Welling
Jeff Welling

Reputation: 1725

How to define class in python?

I'm trying to define a class in Python and use it in bpython, but none of the examples that I've found have worked successfully and I can't figure out why.

In fubar.py:

class Fubar:
   def fubar():
      print 'fubar'

In bpython:

>>> import fubar
>>> Fubar()
Traceback (most recent call last):
  File "<input>", line 1, in <module>
NameError: name 'Fubar' is not defined

Why bpython? Because it supports history and tab-completion OOB.

Every example of python class definitions I've found looks like a variant of what I've used, which is why I don't understand why Fubar() is undefined. Thoughts, comments?

Python 2.6.5 (I don't get to pick the Python version in use) bpython 0.9.5.2

I come from a Ruby background, if that helps explain the confusion to anyone.

Upvotes: 1

Views: 166

Answers (1)

user2555451
user2555451

Reputation:

Your current code is importing the module fubar that contains the class Fubar. However, Python does not implicitly know this. Instead, you have to explicitly tell it where Fubar is.

To do so, make your code like this:

fubar.Fubar()

Or, change your import-statement to this:

from fubar import Fubar
Fubar()  # This will now work

Here is a reference on importing.

Upvotes: 7

Related Questions