Why can't I run this test class?

K

Kermit Mei

Dear all,
I'm a newbie for python, and I write a program to test how to
implement a class:

#!/usr/bin/env
python

class Test:
'My Test class'
def __init__(self):
self.arg1 = 1

def first(self):
return self.arg1

t1 = Test

print t1.first()


#################################

But when I run it, some errors take:

$ ./Test.py
Traceback (most recent call last):
File "./Test.py", line 13, in <module>
print t1.first()
TypeError: unbound method first() must be called with Test instance as
first argument (got nothing instead)

What I want is as the following c++ code do:

class Test
{
public:
Test()
:arg1(1)
{/*Do nothing*/}

int first() const
{ return arg1; }
protected:
int arg1;
};

void main(void)
{
Test t1;
std::cout << t1.first;
}


Hope your help.
Thanks

Kermit
 
U

Ulrich Eckhardt

Kermit said:
#!/usr/bin/env
python

class Test:
'My Test class'
def __init__(self):
self.arg1 = 1

def first(self):
return self.arg1

t1 = Test

't1' is now an alternative name for 'Test'. What you wanted instead was to
instantiate 'Test', which you do with this syntax:

t1 = Test()

print t1.first()

't1.first' or 'Test.first' is a function that takes a single argument (by
convention, that should be an instance of 'Test'). However, no such
instance is provided:
TypeError: unbound method first() must be called with Test instance as
first argument (got nothing instead)


Note that you can invoke the 'first' function in two ways:

t1.first()
Test.first(t1)


Uli
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,954
Messages
2,570,116
Members
46,704
Latest member
BernadineF

Latest Threads

Top