开发者

What is the difference between self and object parameters in __repr__ method?

I already know the difference between old-style class (class 开发者_运维技巧Foo()...) and new-style class (class Foo(object)...). But, what is the difference between that :

class Foo(object):
  def __repr__(self):
    return 'foo'

and

class Foo(object):
  def __repr__(object):
    return 'foo'

Thanks.


The difference is that in one case you called the variable that holds the instance self and in another case you called it object. That's the only difference.

The self variable is explicit in Python, and you can call it whatever you want. self is just the convention everyone uses for readability.

For example, this works just fine:

>>> class Foo(object):
...   def __init__(bippity, colour):
...     bippity.colour = colour
...   def get_colour(_):
...     return _.colour
... 
>>> f = Foo('Blue')
>>> f.get_colour()
'Blue'

But it's pretty damn confusing. :)


This is like saying;

class Foo(object):
    def __init__(self):
        self.a="foo"
    def __repr__(bar):
        return bar.a

The variable name bar has no meaning whatsoever. It is just a reference to self.


As others have pointed out, the name of the first parameter in a class method is merely a convention, you can name it anything you want. BUT DON'T. Always name it self, or you will be confusing everyone. In particular, your example names it object which obscures a built-in name, and so is doubly bad.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜