How is an argument about itself magically passed to instance methods?

I am doing a flow academy academy and I have little experience with Ruby. I do not understand why a function check_angles(self)needs a parameter self.

The reason I got confused is because I don't understand what passes the self parameter to the function when it is called. It seems that the function call (the last line of the code block) is passed implicitly, but the function requires me to be explicitly defined as a parameter.

Why is this?

class Triangle(object):
    def __init__(self, angle1, angle2, angle3):
        self.angle1 = angle1
        self.angle2 = angle2
        self.angle3 = angle3

    number_of_sides = 3

    def check_angles(self):
        sum_angles = self.angle1 + self.angle2 + self.angle3
        if sum_angles == 180:
            return True
        else:
            return False

    tri = Triangle(45,34,78)
    tri.check_angles(EMPTY BUT WHY)
+4
source share
2 answers

, Python, , Foo bar(self) , , instancemethod, "" , foo_inst.bar() Foo.bar(foo_inst).

class Foo(object):
    def bar(self):
        print "called bar on %s" % self

foo_inst = Foo()

# these 2 calls are equivalent
foo_inst.bar()
Foo.bar(foo_inst)

, :

>>> Foo.bar
<unbound method Foo.bar>

>>> Foo().bar
<bound method Foo.bar of <__main__.Foo object at 0x10675ecd0>>

, , bar self, Foo , self , .

, self , arg0 ( stifflersmom allyourbase).

. Python @https://docs.python.org/2/howto/descriptor.html , , .


, , :

class Foo(object):
    pass

def bar(arg0):
    print "called bar with %s" % arg0

Foo.bar = bar

Foo().bar()  # prints: called bar with <Foo object at 0x10675b2d0>

. ( monkeypatching) , Python, A) ( - , , , ) B) ( , , , /IDE, ).

+8

tri.check_angles(), , check_angles . , . tri - , self.

self , .

class A():
    def __init__(self):
        self.x = 2

>>> a = A()
>>> b = A()
>>> print a.x
2
>>> print b.x
2
>>> a.x = 5
>>> print a.x
5
>>> print b.x
2

self.x x, x , x all .

, .

0

Source: https://habr.com/ru/post/1536586/


All Articles