TE
TechEcho
Home24h TopNewestBestAskShowJobs
GitHubTwitter
Home

TechEcho

A tech news platform built with Next.js, providing global tech news and discussions.

GitHubTwitter

Home

HomeNewestBestAskShowJobs

Resources

HackerNews APIOriginal HackerNewsNext.js

© 2025 TechEcho. All rights reserved.

Python: Why can’t we write list.len()?

4 pointsby ceronmanabout 9 years ago

2 comments

ThatGeoGuyabout 9 years ago
&gt; It’s become part of the “modern C++ dogma” that free functions are part of a<p>&gt; type’s interface, just like public members. But some things that are part of a<p>&gt; type’s interface, you call function-style; others, you call dot-style—and,<p>&gt; because there’s no rhyme or reason behind the distinction, you just have to<p>&gt; memorize which are which. And, when designing types, and protocols for those<p>&gt; types to interact with, you have to pick one arbitrarily, and be careful to be<p>&gt; consistent everywhere.<p>Is this really it though? I don&#x27;t agree that &quot;there&#x27;s no rhyme or reason behind the distinction.&quot; In fact, it&#x27;s probably because non-member functions improve encapsulation [1], and because it is not possible to calculate the length of an internal buffer in C++ from outside the class. Unlike in Python, you can&#x27;t access &quot;private&quot; or implementation specific members in a C++ class, so getting the length of a list or vector is something that has to be part of the class. On the other hand, you can access elements of a class without needing the underlying implementation, so it&#x27;s reasonable to write a find procedure that is separate from the class itself.<p>For this reason, you&#x27;re not &quot;pick[ing] one [protocol] arbitrarily,&quot; you&#x27;re doing it to preserve encapsulation and thus have a stronger object orientation. Perhaps the author can shed some light on what they meant here.<p>EDIT: minor formatting of quote<p>[1] <a href="http:&#x2F;&#x2F;www.drdobbs.com&#x2F;cpp&#x2F;how-non-member-functions-improve-encapsu&#x2F;184401197" rel="nofollow">http:&#x2F;&#x2F;www.drdobbs.com&#x2F;cpp&#x2F;how-non-member-functions-improve-...</a>
w8rbtabout 9 years ago
Because len() is a global function. That&#x27;s perfectly fine in an OO system (everything does not have to be an object, attribute or method). Sure, it&#x27;s not as consistent as anything.len(), but it works just fine. That&#x27;s often the reason why Ruby claims to be a cleaner OO implementation than Python.<p>To me, Python really shows its warts when reversing a string. Something you never do out side of school (or on big ending to little endinan conversions).<p>In Python 2:<p><pre><code> string[::-1] </code></pre> In Ruby:<p><pre><code> string.reverse() </code></pre> Now that&#x27;s mind boggling and totally yucky.