Why the syntax for open() and .read() is different?
Question: This is a newbie question, but I looked around and I'm having trouble finding
anything specific to this question (perhaps because it's too simple/obvious to
others).

So, I am working through Zed Shaw's "Learn Python the Hard Way" and I am on
exercise 15. This isn't my first exposure to python, but this time I'm really
trying to understand it at a more fundamental level so I can really do
something with a programming language for once. I should also warn that I
don't have a good background in object oriented programming or fully
internalized what objects, classes, etc. etc. are.

Anyway, here is the exercise. The ideas is to understand basic file opening
and reading:

    
    
    from sys import argv
    
    script, filename = argv
    
    txt = open(filename)
    
    print "Here's your file %r:" % filename
    print txt.read()
    
    print "I'll also ask you to type it again:"
    file_again = raw_input("> ")
    
    txt_again = open(file_again)
    
    print txt_again.read()
    
    txt.close()
    txt_again.close()
    

My question is, why are the `open` and `read` functions used differntly?

For example, to read the example file, why don't/can't I type `print
read(txt)` on line 8?  
Why do I put a period in front of the variable and the function after it?  
Alternatively, why isn't line 5 written `txt = filename.open()`?

This is so confusing to me. Is it simply that some functions have one syntax
and others another syntax? Or am I not understanding something with respect to
how one passes variables to functions.


Answer: ## Syntax

Specifically to the syntactical differences: _open()_ is a function, _read()_
is an object **method**.

When you call the _open()_ function, it returns an object (first _txt_ , then
_txt_again_).

_txt_ is an **object** of class _file_. Objects of class _file_ are defined
with the method _read()_. So, in your code above:

    
    
    txt = open(filename)
    

Calls the _open()_ function and assigns an object of class _file_ into _txt_.

Afterwards, the code:

    
    
    txt.read()
    

calls the method _read()_ that is associated with the object _txt_.

## Objects

In this scenario, it's important to understand that **objects** are defined
not only as data entities, but also with built-in actions against those
entities.

e.g. A hypothetical object of class _car_ might be defined with _methods_ like
_start_engine()_ , _stop_engine()_ , _open_doors()_ , etc.

So as a parallel to your file example above, code for creating and using a car
might be:

    
    
    my_car = create_car(type_of_car)
    my_car.start_engine()
    

[(Wikipedia entry on OOP.)](https://en.wikipedia.org/wiki/Object-
oriented_programming)

