Kurda Yon wrote:
Hi,

I start to learn the object oriented programing in Python. As far as I
understood, every class has a set of corresponding methods and
variables. For me it is easy to understand a method as a one-argument
function associated with a class. For example, if I call "x.calc" and
"y.calc" and if "x" and "y" belongs to different classes I, actually,
call to different function (the first one is associated with the first
class and the second one with the second class). If "x" and "y"
belongs to the same class, the "x.calc" and "y.calc" refer to the same
function (but called with different arguments ("x" and "y",
respectively)).

In the above described case we have one-argument function. But what
should we do if we one two have a two-argument function. For example,
we want to have a method "calc" which take two objects and returns one
value. How do we call this method? Like "x&y.calc"? Or just calc(x,y)?
In the case of the one-argument functions Pythons automatically decide
which function to call (associated with the first class or with the
second class). Will it be the same in the case of the two-argument
function.

I am not sure that I am clear. If I am not clear, just ask me. I will
try to reformulate my questions.

Thank you.

You are very close to being correct. Classes have 'methods' (which can take any number of arguments) that act like functions and 'attributes' that are normally stored values in the class instance. I say "normally" because there is an advanced method of making attributes actually be functions (even though they appear externally as values).

class foo(object):
    def do_square(self, v):
        return v*v


# create an instance of our class
a = foo()
# call the do_square method with a value
a.do_square(10)

>>> 100

# call the do_square method with a different value
a.do_seuare(2)

>>> 4

or maybe

class bar(object):
    def __init__(self):
        self.total = 0

    def accumulate(self, v):
        self.total += v

# create an instance of our new class
b = bar()

# call the accumulate method with several values
b.accumulate(5)
b.accumulate(6)
b.accumulate(7)

# print the value stored in the total attribute of our class instance
print b.total

>>> 18

Hope this helps.

-Larry
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to