Python Script Files
The examples shown so far have used a Python interpreter that provides a mode in which you can interact with Python and which is useful for simple experiments. However, it is a little inconvenient if you want to do large processing because you have to enter a program every time. In such a case, you can save a Python program as a file and execute it (at one time). This next section provides examples of Python script files.
Saving in a File
Open your text editor and create a hungry.py
file. The hungry.py
file has only one line in it, as shown here:
print("I'm hungry!")
Then, open a Terminal (Command Prompt for Windows) and move to the location where the hungry.py
file was created. Execute the python
command with the argument of the filename, hungry.py
. Here,
it is assumed that hungry.py
is located in the ~/deep-learning-from-zero/ch01
directory (in the source code provided by this book, hungry.py
is located under the ch01
directory):
$ cd ~/deep-learning-from-zero/ch01 # Move to the directory $ python hungry.py I'm hungry!
Thus, you can use the python hungry.py
command to run the Python program.
Classes
So far, you have learned about data types such as int
and str
(you can use the type()
function to check the object type). These data types are called built-in data types since they are built into Python. Here, you will define a new class to create your data type. You can also define your original method (function for a class) and attributes.
In Python, you can use the class
keyword to define a class. You must use the following format:
class name: def __init__ (self, argument, …): # Constructor ... def method name 1 (self, argument, …): # Method 1 ... def method name 2 (self, argument, …): # Method 2 ...
The __init__
method is a special method for initialization. This method for initialization is also referred to as a constructor and is called only once when the instance of a class is created. In Python, you need to write self
explicitly as the first argument of a method to represent yourself (your instance). (This practice may seem strange to those who are familiar with other languages.)
Create a class as a simple example as shown below, and save the following program as man.py
:
class Man: def __init__(self, name): self.name = name print("Initialized!") def hello(self): print("Hello " + self.name + "!") def goodbye(self): print("Good-bye " + self.name + "!") m = Man("David") m.hello() m.goodbye()
Execute man.py
from the Terminal:
$ python man.py Initialized! Hello David! Good-bye David!
Here, you defined a new class, Man
. In the preceding example, an instance (object), m, was created from the Man
class.
The constructor (initialization method) of the Man
class takes name
as an argument and uses it to initialize the instance variable, self.name
. An instance variable is a variable that is stored in each instance. In Python, you can create and access an instance variable by appending an attribute name to self
.