Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #25444
| From | Terry Reedy <tjreedy@udel.edu> |
|---|---|
| Subject | Re: Style question: metaclass self vs cls? |
| Date | 2012-07-16 18:21 -0400 |
| References | <50043377$0$29978$c3e8da3$5496439d@news.astraweb.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.2192.1342477286.4697.python-list@python.org> (permalink) |
On 7/16/2012 11:29 AM, Steven D'Aprano wrote: > Here's a style question for you: in a metaclass, what should I call the > instance parameter of methods, "cls" or "self"? > > class ExampleMeta(type): > def method(self, *args): ... > > I'm not quite sure if that feels right. On the one hand, self is the > ExampleMeta instance alright... but on the other, self is actually a > class, so I feel I want to call it "cls" rather than "self", which makes > it more obvious that you're looking at a metaclass. I have never seriously written a metaclass, but as a reader I would prefer 'cls'. > On the third-hand, it may be confusing that the argument is called "cls" > but not decorated with classdecorator. To me, that reinforces 'looking as a metaclass'. An @classmethod in a class is a class method specific to the particular class. A method in a metaclass is a method common to all classes of the metaclass. They could be written differently, yet calling the first param 'cls' either way seems reasonable. > I'm very slightly leaning towards writing metaclasses like this: > > class ExampleMeta(type): > def __new__(meta, *args): ... > def method(cls, *args): ... > > class Example(metaclass=ExampleMeta): > def another_method(self): ... > What do others do? Not too many people write real metaclasses. Python lets you chose. Have you looked at the C code of type? (Not that you are bound by it.) -- Terry Jan Reedy
Back to comp.lang.python | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
Style question: metaclass self vs cls? Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2012-07-16 15:29 +0000
Re: Style question: metaclass self vs cls? Terry Reedy <tjreedy@udel.edu> - 2012-07-16 18:21 -0400
Re: Style question: metaclass self vs cls? alex23 <wuwei23@gmail.com> - 2012-07-16 23:10 -0700
Re: Style question: metaclass self vs cls? Ian Kelly <ian.g.kelly@gmail.com> - 2012-07-17 10:35 -0600
Re: Style question: metaclass self vs cls? Michele Simionato <michele.simionato@gmail.com> - 2012-07-17 05:23 -0700
Re: Style question: metaclass self vs cls? Ian Kelly <ian.g.kelly@gmail.com> - 2012-07-17 10:34 -0600
Re: Style question: metaclass self vs cls? Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2012-07-18 02:50 +0000
csiph-web