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

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

    The 'self' parameter keeps the current calling object.

    class class_name:
        class_variable
        def method_name(self,arg):
            self.var=arg 
    obj=class_name()
    obj.method_name()
    

    here, the self argument holds the object obj. Hence, the statement self.var denotes obj.var

提交回复
热议问题