On Sun, Sep 20, 2009 at 4:42 AM, Dave Angel <da...@ieee.org> wrote: > > > Peng Yu wrote: >> >> <snip> >>> >>> def __str__(self): >>> return 'Bin(%s, %s)' %(self.x, self.y) >>> __repr__ =_str__ >>> >>> Please use an initial capital letter when defining a class, this is >>> the accepted way in many languages!!! >>> >> >> I want to understand the exact meaning of the last line ('__repr__ >> __str__'). Would you please point me to the section of the python >> manual that describes such usage. >> >> Regards, >> Peng >> >> > > I don't know where to look in the various manuals, but what we have here are > class attributes. Inside the class definition, each method definition is a > class attribute. In addition, any "variable" definition is a class > attribute as well. For example, > class MyClass(object): > counter = 0 > def __str__(self): > return "Kilroy"+str(self.value) > def __init__(self, num): > self.value = num+1 > > counter is a class attribute, initialized to zero. That attribute is shared > among all the instances, unlike data attributes, which are independently > stored in each instance. > > Anyway, the __repr__ = __str__ simply copies a class attribute. So now > you have two names which call the same method. To explicitly call one of > them, you might use:
Is __repr__ = __str__ copy by reference or by value? If I change __str__ later on, will __repr__ be changed automatically? Regards, Peng > obj = MyClass(42) > mystring = obj.__str__() #mystring is now "Kilroy43" > > > But normally, you don't directly call such methods, except for debug > purposes. They are implicitly called by functions like print(). > > > -- http://mail.python.org/mailman/listinfo/python-list