... j += 1
... i += 1
...
Pos: (0,0)
Pos: (0,1)
Pos: (0,2)
Pos: (1,0)
Pos: (1,1)
Pos: (1,2)
Pos: (2,0)
Pos: (2,1)
Pos: (2,2)
You can control loops by using the break
and continue
keywords. break
exits the loop and continues processing immediately afterward, and continue
jumps to the next loop iteration.
Other languages — such as PHP — read and process an entire file before executing it, which means you can call a function before it is defined because the compiler reads the definition of the function before it tries to call it. Python is different: If the function definition has not been reached by the time you try to call it, you get an error. The reason behind this behavior is that Python actually creates an object for your function, and that in turns means two things. First, you can define the same function several times in a script and have the script pick the correct one at runtime. Second, you can assign the function to another name just by using =
.
A function definition starts with def
, followed by the function name, parentheses and a list of parameters, and then a colon. The contents of a function need to be indented at least one level beyond the definition. So, using function assignment and dynamic declaration, you can write a script that prints the correct greeting in a roundabout manner:
>>> def hello_english(Name):
... print "Hello, " + Name + "!"
...
>>> def hello_hungarian(Name):
... print "Szia, " + Name + "!"
...
>>> hello = hello_hungarian
>>> hello("Paul") Szia, Paul!
>>> hello = hello_english
>>> hello("Paul")
Notice that function definitions include no type information. Functions are typeless, as we said. The upside of this is that you can write one function to do several things:
>>> def concat(First, Second):
... return First + Second
...
>>> concat(["python"], ["perl"])
['python', 'perl']
>>> concat("Hello, ", "world!")
'Hello, world!'
That demonstrates how the return
statement sends a value back to the caller, but also how a function can do one thing with lists and another thing with strings. The magic here is being accomplished by the objects. You can write a function that tells two objects to add themselves together, and the objects intrinsically know how to do that. If they don't — if, perhaps, the user passes in a string and an integer — Python catches the error for you. However, it is this hands-off, "let the objects sort themselves out" attitude that makes functions so flexible. The concat()
function could conceivably concatenate strings, lists, or zonks — a data type someone created herself that allows addition. The point is that you do not limit what your function can do — clichй as it might sound, the only limit is your imagination!
After having read this far, you should not be surprised to hear that Python's object orientation is flexible and likely to surprise you if you have been using C-like languages for several years.
The best way to learn Python OOP is to just do it. So, here is a basic script that defines a class, creates an object of that class, and calls a function:
class dog(object):
def bark(self):
print "Woof!"
fluffy = dog()
fluffy.bark()
Defining a class starts, predictably, with the class
keyword, followed by the name of the class you are defining and a colon. The contents of that class need to be indented one level so that Python knows where each class stops. Note that the object
inside parentheses is there for object inheritance, which is discussed later. For now, the least you need to know is that if your new class is not based on an existing class, you should put object
inside parentheses as shown in the previous code.
Functions inside classes work in much the same way as normal functions do (although they are usually called methods), with the main difference being that they should all take at least one parameter, usually called self
. This parameter is filled with the name of the object on which the function was called, and you need to use it explicitly.
Creating an instance of a class is done by assignment. You do not need any new
keyword, as in some other languages — you just provide empty parentheses. You call a function of
that object by using a period and the name of the class to call, with any parameters passed inside parentheses.
Class and Object Variables
Each object has its own set of functions and variables, and you can manipulate those variables independent of objects of the same type. Additionally, some class variables are set to a default value for all classes and can also be manipulated globally.
This script demonstrates two objects of the dog
class being created, each with its own name:
class dog(object):
name = "Lassie"
def bark(self):
print self.name + " says 'Woof!'"
def setName(self, name):
self.name = name
fluffy = dog()
fluffy.bark()
poppy = dog()
poppy.setName("Poppy")
poppy.bark()
That outputs the following:
Lassie says 'Woof!'
Poppy says 'Woof!'
Each dog starts with the name Lassie
, but it gets customized. Keep in mind that Python assigns by reference by default, meaning each object has a reference to the class's name
variable, and as you assign that with the setName()
method, that reference is lost. What this means is that any references you do not change can be manipulated globally. Thus, if you change a class's variable, it also changes in all instances of that class that have not set their own value for that variable. For example:
class dog(object):
name = "Lassie"
color = "brown"
fluffy = dog()
poppy = dog()
print fluffy.color
dog.color = "black"
print poppy.color
poppy.color = "yellow"
print fluffy.color
print poppy.color
So, the default color of dogs is brown — both the fluffy
and poppy dog
objects start off as brown. Then, with dog.color
, the default color is set to black, and because neither of the two objects has set its own color value, they are updated to be black. The third to last line uses poppy.color
to set a custom color value for the poppy
object — poppy
becomes yellow, but fluffy
and the dog
class in general remain black.
Constructors and Destructors
To help you automate the creation and deletion of objects, you can easily override two default methods: __init__
and __del__
. These are the methods called by Python when a class is being instantiated and freed, known as the constructor and destructor , respectively.
Читать дальше