Why do you need explicitly have the “self” argument in a Python method?

前端 未结 10 1383
借酒劲吻你
借酒劲吻你 2020-11-22 11:53

When defining a method on a class in Python, it looks something like this:

class MyClass(object):
    def __init__(self, x, y):
        self.x = x
        se         


        
10条回答
  •  轮回少年
    2020-11-22 12:34

    It's to minimize the difference between methods and functions. It allows you to easily generate methods in metaclasses, or add methods at runtime to pre-existing classes.

    e.g.

    >>> class C(object):
    ...     def foo(self):
    ...         print "Hi!"
    ...
    >>>
    >>> def bar(self):
    ...     print "Bork bork bork!"
    ...
    >>>
    >>> c = C()
    >>> C.bar = bar
    >>> c.bar()
    Bork bork bork!
    >>> c.foo()
    Hi!
    >>>
    

    It also (as far as I know) makes the implementation of the python runtime easier.

提交回复
热议问题