0

I am starting to work with classes in Python, and am learning how to create functions within classes. Does anyone have any tips on this sample class & function that I am testing out?

class test:
    def __init__(self):
        self.a = None
        self.b = None
        self.c = None

    def prod(self): 
        return self.a * self.b

trial = test
trial.a = 4
trial.b = 5
print trial.prod

Ideally the result would be to see the number 20.

3
  • 6
    You need to use: trial = test() and trial.prod() Commented Jan 29, 2014 at 19:09
  • Classes are objects too. No instance is created above - see what trial is. Commented Jan 29, 2014 at 19:09
  • Good point, done. That now leaves the result as <bound method of test.prod of <__main__.test instance at 0x000....>> Commented Jan 29, 2014 at 19:11

2 Answers 2

5

You need to:

  1. Create an instance of test.

  2. Invoke the prod method of that instance.

Both of these can be accomplished by adding () after their names:

trial = test()
trial.a = 4
trial.b = 5
print trial.prod()

Below is a demonstration:

>>> class test:
...     def __init__(self):
...         self.a = None
...         self.b = None
...         self.c = None
...     def prod(self):
...         return self.a * self.b
...
>>> trial = test()
>>> trial.a = 4
>>> trial.b = 5
>>> print trial.prod()
20
>>>

Without the parenthesis, this line:

trial = test

is simply assigning the variable trial to class test itself, not an instance of it. Moreover, this line:

print trial.prod

is just printing the string representation of test.prod, not the value returned by invoking it.


Here is a reference on Python classes and OOP.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks very much. First question ever on the site!
1

Ideally you could also pass in the values to a, b, c as parameters to your object's constructor:

class test:
    def __init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c

    def prod(self): 
        return self.a * self.b

Then, constructing and calling the function would look like this:

 trial = test(4, 5, None)
 print trial.prod()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.