classmethod & staticmethod

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Wed Jul 25 08:18:44 EDT 2007


En Tue, 24 Jul 2007 21:55:17 -0300, Alex Popescu  
<nospam.themindstorm at gmail.com> escribió:

> Neil Cerutti <horpner at yahoo.com> wrote in news:eRwpi.36813$G23.28496
> @newsreading01.news.tds.net:
>> On 2007-07-25, Alex Popescu <nospam.themindstorm at gmail.com> wrote:
>>> As a matter of style, how do you figure out that class_list is
>>> a class attribute and not an instance attribute? (I don't
>>> remember seeing anything in the PEP describing the coding
>>> style).
>>
>> Check out dir(MyClass) and dir(MyClass()) for some insight, if it
>> turns out that it matters.
>
> I must confess that I am a bit confused by this advise, as both are
> returning exactly the same thing.

Perhaps he meant to say vars(MyClass) and vars(MyClass())

>> Preferably, the user of a class
>> doesn't have to really think about it much.
> I know that this would be prefered, but in case you are getting 3rd party
> code and you modify a class attribute without knowing it is a class
> attribute then you may get into trouble (indeed the real problem is with
> the designer of the 3rd party code, but still I think it is a valid
> concern).

Well, you should read its documentation before modifying 3rd. party  
code... :)

If you access (read) an attribute through an instance (let's say, you  
write x = self.name inside a method) the attribute is first searched in  
the instance, and when not found, in the class (The actual rules are more  
complicated but this will suffice for now). If you assign an attribute, it  
is always set on the instance (never on the class). So you can use a class  
attribute as a default value for an instance attribute. For this use case,  
you don't care whether it's an instance attribute or class attribute:

py> class Title:
...   color = "white"
...   def __init__(self, text, color=None):
...     self.text = text
...     if color is not None:
...       self.color = color
...
py> t1 = Title("Hello")
py> vars(t1)
{'text': 'Hello'}
py> t1.color
'white'
py> Title.color
'white'
py> t1.color = "red"
py> vars(t1)
{'color': 'red', 'text': 'Hello'}
py> Title.color
'white'
py> t2 = Title("Goodbye", "blue")
py> vars(t2)
{'color': 'blue', 'text': 'Goodbye'}


-- 
Gabriel Genellina




More information about the Python-list mailing list