Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #61986
| From | Ned Batchelder <ned@nedbatchelder.com> |
|---|---|
| Subject | Re: Type of an object: ‘obj.__class__’ versus ‘type(obj)’ |
| Date | 2013-12-15 21:50 -0500 |
| References | <7wk3f5k1gm.fsf@benfinney.id.au> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.4166.1387162238.18130.python-list@python.org> (permalink) |
On 12/15/13 8:51 PM, Ben Finney wrote: > Howdy all, > > What is the Pythonic way to determine the type of an object? Are there > multiple valid ways, and when should each be used? > > We have ‘obj.__class__’, an attribute bound to the object's class. Or is > it? When is that true, and when should we not rely on it? > > We have ‘type(obj)’, calling the constructor for the ‘type’ type in > order to get a reference to the type of ‘obj’. Or is it? When is that > true, and when should we not rely on it? > > Are there other ways to get at the type of a Python object? What reasons > are there to choose or avoid them? > Generally, my answer would be, "You probably don't need the type as much as you think you do." But when you do need it, type(x) is better than x.__class__, simply because we should always favor builtin functions over direct access of dunder-names where possible. Also, don't overlook isinstance(). -- Ned Batchelder, http://nedbatchelder.com
Back to comp.lang.python | Previous | Next | Find similar | Unroll thread
Re: Type of an object: ‘obj.__class__’ versus ‘type(obj)’ Ned Batchelder <ned@nedbatchelder.com> - 2013-12-15 21:50 -0500
csiph-web