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

前端 未结 10 1408
借酒劲吻你
借酒劲吻你 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:31

    I like to quote Peters' Zen of Python. "Explicit is better than implicit."

    In Java and C++, 'this.' can be deduced, except when you have variable names that make it impossible to deduce. So you sometimes need it and sometimes don't.

    Python elects to make things like this explicit rather than based on a rule.

    Additionally, since nothing is implied or assumed, parts of the implementation are exposed. self.__class__, self.__dict__ and other "internal" structures are available in an obvious way.

提交回复
热议问题