简体   繁体   中英

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM