[Tutor] Error when trying to use classes
George Fischhof
george at fischhof.hu
Tue Feb 7 13:59:08 EST 2017
2017-02-07 16:34 GMT+01:00 Rafael Skovron <rskovron at gmail.com>:
> I'm trying to learn how to use Classes but I keep getting NameErrors no
> matter what code I put into the script.
>
> Any ideas why?
>
> My general workflow is I edit in vim, then invoke python3 interpreter,
> import the module and try to use the Class and methods from the class.
>
> For example, importing customer.py and assigning this object yields:
>
> >>> rafael = Customer('rafael',100.0)
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> NameError: name 'Customer' is not defined
>
>
>
> class Customer(object):
> """A customer of ABC Bank with a checking account. Customers have
> the following properties:
> Attributes: name: A string representing the customer's
> name. balance: A float tracking the current balance of the
> customer's account. """
>
> def __init__(self, name, balance=0.0):
> """Return a Customer object whose name is *name* and starting
> balance is *balance*."""
> self.name = name
> self.balance = balance
>
> def withdraw(self, amount):
> """Return the balance remaining after withdrawing *amount*
> dollars."""
> if amount > self.balance:
> raise RuntimeError('Amount greater than available balance.')
> self.balance -= amount
> return self.balance
>
> def deposit(self, amount):
> """Return the balance remaining after depositing *amount*
> dollars."""
> self.balance += amount
> return self.balance
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
Hi,
with this statement:
>>> rafael = Customer('rafael',100.0)
you (the program) creates an instance of Customer class
to import the class (this is the first), you should use the import
statement:
>>> from customer import Customer
after this the program will work.
BR,
George
PS.: pycharm from JetBrains is a very good python ide. ... (instead of vim
;-) )
More information about the Tutor
mailing list