473,659 Members | 2,656 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

why descriptors? (WAS: Make staticmethod objects callable?)

Steven Bethard wrote:
(For anyone else out there reading who doesn't already know this,
Steven D'Aprano's comments are easily explained by noting that the
__get__ method of staticmethod objects returns functions, and classes
always call the __get__ methods of descriptors when those descriptors
are class attributes:
Steven D'Aprano wrote: Why all the indirection to implement something which is, conceptually,
the same as an ordinary function?


While I wasn't around when descriptors and new-style classes were
introduced, my guess is that it's mainly because what you *usually* want
when defining a function in a class is for that function to be an
instance method. That is, the following code::

class C(object):
def foo(self):
pass
c = C()
c.foo()

should be much more common than::

class C(object):
def foo():
pass
C.foo()

because the whole point of creating a class is to allow you to create
instances. But if ``C.foo`` and ``c.foo`` are just regular functions,
then how will ``c.foo()`` get the ``self`` argument? Certainly a normal
``foo()`` shouldn't be inserting a magical ``self`` argument. So *some*
indirection has to happen when a function is used in a class.

Python's solution to this problem is to introduce descriptors, which are
the "something" that classes have to do. All classes invoke __get__
whenever any of their attributes are accessed. With a normal function
object, invoking __get__ turns it into an instance method:
class C(object): .... pass
.... def foo(self): .... pass
.... foo <function foo at 0x00E69530> foo.__get__(C() , C) <bound method C.foo of <__main__.C object at 0x00E738F0>> class C(object): .... def foo(self):
.... pass
.... C().foo

<bound method C.foo of <__main__.C object at 0x00E59C50>>

As a result, if you want to have a callable as a class attribute and you
don't want that callable to give you an instance method when you access
it, you can't use a regular Python function. Personally, I think that's
pretty reasonable since 99% of the time, I *do* want an instance method[1].

STeVe

[1] The other 1% of the time, I pretty much always want a classmethod.
I'm still convinced that staticmethods are basically silly when I can
just declare a module level function. ;)
Mar 1 '06 #1
0 1301

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
1902
by: Denis S. Otkidach | last post by:
I've noticed that the order of attribute lookup is inconsistent when descriptor is used. property instance takes precedence of instance attributes: >>> class A(object): .... def _get_attr(self): .... return self._attr .... attr = property(_get_attr) .... >>> a=A()
4
5920
by: Michal Vitecek | last post by:
hello everyone, today i've come upon a strange exception, consider the following file test.py: --- beginning of test.py --- class A(object): def method1(parA): print "in A.method1()"
68
4342
by: Marco Bubke | last post by:
Hi I have read some mail on the dev mailing list about PEP 318 and find the new Syntax really ugly. def foo(x, y): pass I call this foo(1, 2), this isn't really intuitive to me! Also I don't like the brackets.
0
1609
by: Robin Becker | last post by:
A colleague wanted to initialize his class __new__ and tried code resembling this #######################1 class Metaclass (type): def __init__(cls, name, bases, *args, **kwargs): super(Metaclass, cls).__init__(cls, name, bases, *args, **kwargs) print 'cls=',cls, cls.__new cls.__new__ = staticmethod(cls.__new) def __new(self,cls,*args):
11
25729
by: cjl | last post by:
Hey all: I want to convert strings (ex. '3', '32') to strings with left padded zeroes (ex. '003', '032'), so I tried this: string1 = '32' string2 = "%03s" % (string1) print string2 >32
10
6997
by: Nicolas Fleury | last post by:
Hi everyone, I was wondering if it would make sense to make staticmethod objects callable, so that the following code would work: class A: @staticmethod def foo(): pass bar = foo() I understand staticmethod objects don't need to implement __call__ for
12
1438
by: bruno at modulix | last post by:
Hi I'm currently playing with some (possibly weird...) code, and I'd have a use for per-instance descriptors, ie (dummy code): class DummyDescriptor(object): def __get__(self, obj, objtype=None): if obj is None: return self return getattr(obj, 'bar', 'no bar')
3
2165
by: redefined.horizons | last post by:
I've been reading about Python Classes, and I'm a little confused about how Python stores the state of an object. I was hoping for some help. I realize that you can't create an empty place holder for a member variable of a Python object. It has to be given a value when defined, or set within a method. But what is the difference between an Attribute of a Class, a Descriptor in a Class, and a Property in a Class?
8
3361
by: M.Endraszka | last post by:
Hi, I am writing a simple irc-like server and came across weird behavior while debugging. Could anyone tell me why the following happens : I have a class which stores pipe descriptors as a member field. Descriptors are initialized with pipe(descr) in class constructor. Then I have an array of objects of this class, preferably a STL vector. If I initialize the vector with:
0
8427
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8332
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8851
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8525
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8627
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6179
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5649
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4335
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
1737
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.