1

I'm learning python and I'm finding python methods inconsistent.

Why is it that Len is len(s) whereas if I want to read a file I do f.read() and why do I have os.read() which is completely different that f.read().

What's the rationale of having such inconsistency in python.

Why cannot I do s.len() just like I can do f.read()? Why does os.read() exist when f.read() exists.

Mert Köklü
  • 2,183
  • 2
  • 16
  • 20
user855
  • 19,048
  • 38
  • 98
  • 162
  • 1
    Granted, `len()` is a bit different in that it operates on things that implement a specific protocol (and there are others) but why would you expect `f.read()` and `os.read()` _not_ to be different? They're in different modules and do different things. Pretty much all languages have ways to namespace / group / categorize related functionality. – ChrisGPT was on strike Dec 02 '19 at 19:26
  • I think it's just shorthand for common functions but I find this confusing too. – kjmerf Dec 02 '19 at 19:26
  • because one is a function and the other is a method. – juanpa.arrivillaga Dec 02 '19 at 19:28
  • 1
    `os.read` is *very different* than `f.read`. `f` will be a file object, whereas `os.read` is essentially a wrapper around lowever-level file-system functions. It doesn't take a file object, but a file *descriptor*, i.e. a *number*. – juanpa.arrivillaga Dec 02 '19 at 19:32
  • "However, if you learned another object-oriented language before Python, you may have found it strange to use len(collection) instead of collection.len(). This apparent oddity is the tip of an iceberg that, when properly understood, is the key to everything we call Pythonic. The iceberg is called the Python data model, and it describes the API that you can use to make your own objects play well with the most idiomatic language features" Fluent Python (page 3) https://evanli.github.io/programming-book-3/Python/Fluent%20Python.pdf – Perplexabot Dec 02 '19 at 19:50

0 Answers0