-1

Could someone explain to me what the parentheses after the .read(), .truncate()and .close() commands are doing?

I'm confused by why they're empty and why it isn't written as: read(filename), truncate(filename), and close(filename) rather than filename.read(), filename.truncate(), and filename.close()?

But open is written as open(filename) and not filename.open()

martineau
  • 119,623
  • 25
  • 170
  • 301
  • Have you studied `class`es yet? This is a question of functions vs methods. – Carcigenicate Oct 29 '19 at 00:08
  • 1
    @Carcigenicate You are right, in this case the duplicate is not appropriate either. Reopening it. – Selcuk Oct 29 '19 at 00:25
  • 1
    @Selcuk it's more like "unclear what you're asking" than "duplicate"! – csabinho Oct 29 '19 at 00:28
  • 1
    To be fair I think it is pretty clear. The lack of formatting makes it a bit hard to read. – Selcuk Oct 29 '19 at 00:30
  • Well, I don't think we, or even the person who asked, understood what the question is. It seems to be a general confusion about where the data is stored and what functions, classes and instances are. – csabinho Oct 29 '19 at 00:40
  • 1
    It's not `read(filename)`, it's `file.read(number_of_bytes)`. `read()`is a method of the `file`class and the `()` following its name cause it to be called with the argument value inside them (which happens to be optional for this particular method and can be left out). – martineau Oct 29 '19 at 00:53

1 Answers1

3

Those parentheses () are for actually calling a certain function instead of merely referring to it.

Consider for example:

def func():
    return "I am being called!"


print(func)
# <function func at 0x7f41f59a6b70>

print(func())
# I am being called!

Regarding the: func(x) versus x.func() syntax, this is a design / stylistic choice.

The first syntax is associated to procedural design / style, while the second syntax is associated to explicitly object-oriented design / style.

Python (as well as many other general purpose languages) support both.

When func was designed as:

def func(x):
    ...

you would use the procedural style.

When func is designed as:

class MyX(object):
    def func(self):
        ...

you would use the object-oriented style. Note that this would require x to be of type MyX (or a sub-class of it).

More info is available in Python tutorials, e.g. here.

Final note: in some programming languages (notably D and nim) there is the concept of Uniform Function Call Syntax, which basically allows you to write function and then have it called with whichever syntax (procedural or object-oriented) you prefer.

norok2
  • 25,683
  • 4
  • 73
  • 99