Movatterモバイル変換
[0]ホーム
[Python-Dev] Class Methods
Tim Peterstim.one at home.com
Sat Apr 21 19:51:13 EDT 2001
[Thomas Heller]> ...> There are (even in the standard python library) usage> patterns going like this:>> class X:> _inited = 0> def __init__(self, ...):> if not _inited:> <code to set some class attributes>> ....>> This is really not instance but class initialization,> and it is deferred until the first instance has been> created. What if someone need the (calculated) class> attributes before this?I *suspect* you're reading the code incorrectly, but hard to say since thatsnippet doesn't make sense. If the actual test looks like if not X._inited:then, yes, maybe so. But if it looks like if not self._inited:then it's probably aiming at something quite different from class attributefiddling. Whenever you see class X: attr = whatever ... def f(self): ... ... self.attr ...it's *most likely* the case that the class author is *exploiting* thatself.attr will resolve to X.attr if self doesn't have its own attr. This isa memory-saving trick for attrs that *normally* have the same value acrossmost instances. By letting self.attr defer to X.attr, the instance doesn'thave to burn space in its own dict to record attr's value, for so long as theinstance is happy to use the common value. *Binding* to self.attr gives theinstance its own value for attr when the common value is not acceptable, andthen a later reference to self.attr picks that up instead of the class value.Anyway, please point to some specific code in the std library that you thinkis doing class-attr fiddling of the kind you're talking about. Offhand Idon't recall any (but know lots of places that use the trick I justdescribed).
More information about the Python-listmailing list
[8]ページ先頭