Книга: Mastering Blender
Назад: Chapter 11: Working with the Video Sequence Editor
Дальше: Chapter 13: Python Scripting for Blender

Part IV

Blender-Python

Chapter 12

The Blender-Python Interpreter

One of the advanced features of Blender is a fully functional, built-in interpreter for the Python scripting language. This enables you to directly access internal Blender data to automate tasks and create your own tools, as well as greatly enhance the power of several other features, from nodes to the game engine to F-curve drivers. However, in order to take advantage of the power that Python can give you over your Blender work, you must first get a sense of the Python language itself. This chapter provides a brief and gentle introduction to the language, suitable for people unfamiliar with Python and those who have done little or no programming at all.

In this chapter, you will learn to

Introducing Python

The next two chapters of this book are intended to give you a thorough overview of using the Python scripting language in Blender. Because this book is aimed at Blender users and not necessarily at programmers, I am assuming little or no knowledge of programming, but of course any little bit will be helpful. If you have a background in another object-oriented programming language, you should find everything in these chapters to be smooth sailing. On the other hand, if your eyes completely glaze over at terms such as variable, you’ll want to take it slow, but I hope that with a little patience and persistence even those of you in this category will eventually find yourselves able to accomplish what you want to with Python in Blender.

What Is Python?

Python is a widely used, general-purpose, object-oriented scripting language. It is used for everything from research to web programming and has a wide variety of third-party libraries and tools available for it. If you’re reading this, you probably know by now that Python is also the language used for scripting in Blender. I’m going to assume that you don’t know much more than that about Python. If you do, feel free to skip ahead to what you need.

If you’re completely new to Python or to programming, the first question you might ask is, “What does scripting mean?” Indeed, understanding this is central to understanding how Python can be useful to you in the context of Blender, so it’s worth going into a little bit of detail.

How Programs Run

There are two main paradigms for how computer programs run. Some programming languages, such as C and C++, are compiled languages. This means that the programmer writes the program in some plain-text format and sends that program to a piece of software called a compiler. The compiler reads the text program (also called source code) and outputs a binary executable. The binary executable is entirely encoded in ones and zeros and can’t be read by human beings (at least, not without Rain Man-esque abilities of concentration). This paradigm of compiled languages is a classic model, and the insistence of open-source licenses such as the GNU General Public License (GPL) on freely distributed source code is a direct corollary of this paradigm. Open-source licenses such as the GPL are fundamentally intended to ensure that end users have access to software in a format that can be read and understood by humans, rather than only in binary format.

Blender is written primarily in the C language, and its development follows the compiled-languages paradigm. Most Blender users download binaries directly either in .zip files or in system-specific installers. These binaries are provided for the convenience of users, but the license doesn’t require that they be freely available. What is required is that the source be freely available, and it is. You can download the source in an archive file from the Blender home page and also by checking it out of the Subversion repository (this is how developers generally access the code).

The other paradigm for running computer programs is that of interpreted languages. With these languages, the written code is executed by a program called an interpreter, which runs simultaneously with the software that was written in the interpreted language. As an analogy, you can think of compiled languages as being like a book translation from one language to another. The compiler translates source code to machine-readable binary code, and after it has been translated, the binary code is no longer dependent on the source. In the case of interpreted languages, the analogy is (unsurprisingly) that of an interpreter of a speech who communicates simultaneously with a speaker, interpreting what is being said into another language. Both the original speaker and the interpreter need to be working simultaneously in order for the listener to understand the message.

Programs written in interpreted languages (that is, with the intention of being run via an interpreter) are often referred to as scripts. When Python is referred to as a scripting language, it is essentially just another way of saying that it is an interpreted language.

The kinds of tasks that interpreted languages are suited to are not always the same kinds of tasks that compiled languages are suited to. Scripting languages tend to excel at doing small, specific tasks quickly. They typically allow a higher level of abstraction in their syntax, making it possible to carry out complex but common tasks more simply. On the other hand, building large-scale applications is something that may be better approached using compiled languages, because in most cases, the overhead of running the interpreter slows the program’s performance on large, complex tasks. The division of labor in the Blender world between the C language (application development) and Python (scripting) is a perfect example of how these two execution paradigms work together.

Scripting and Blender

In this chapter, you’ll become familiar with the basics of Python and you’ll be introduced to the Python console interface in Blender. Although you won’t always use the integrated console interface when you get to more advanced scripting tasks, it’s a very handy way to interact with the Blender Python interpreter. Blender comes complete with a full installation of Python and all the development tools you need to do scripting, so it is not necessary for you to download Python separately or to deal with the native development environment of freestanding Python installations.

By using Blender’s built-in interpreter and application programming interface (API) to run scripts, you can access Blender assets and functionality. This can be useful for a wide variety of tasks, from automating simple but repetitive steps that would be too tedious to do by hand through the standard Blender interface, to setting up your own macros and tools, to creating sophisticated mathematical visualizations automatically with the stroke of a key. Furthermore, Blender’s Python functionality is deeply integrated, making it possible to access Python in other ways aside from the main script interpreter. In addition to simply running scripts in Blender, you can access Python through the nodes system, use Python for animation drivers, use Python to create constraints, and incorporate full Python functionality in the game engine with Python logic bricks. In the next few chapters, you’ll learn how to do all of these things and how this knowledge can open up a whole new world of Blender functionality to you.

Why Python?

In the years since Python was initially released in 1991, it has become widely used in a host of different application domains. There are several reasons for this. First, Python is relatively easy to learn. For people accustomed to other programming languages, there are syntactic features peculiar to Python that must be learned, but by and large, the functionality people expect from other languages is straightforwardly implemented in Python. For new programmers, Python implements high-level abstractions that can simplify many tasks that would require more-involved solutions in other languages, making Python comparatively easy to start programming with. Indeed, one of the biggest habits for experienced programmers to break when they begin working with Python is the tendency to want to code things in an unnecessarily complex way. Iterating through lists, for example, is done more simply in Python than in other commonly used languages.

Python’s ease of use extends not just to learning the language but also to development. Python code is known for its readability. One of Python’s most notable syntactic idiosyncrasies is that it forces you to write readable code. In Python, the scope of control structures such as for loops and conditionals is determined by the left-side indentation of the line. In other commonly used languages, this is usually handled by some kind of bracketing, and white space, tabs, and spaces are far less important. Python’s approach helps to eliminate many kinds of subtle bracketing errors that plague other languages. In Python, if the pattern of indentation in a script is not well formed, the interpreter will throw up a syntax error and the script will not be executed. If the indentation is well formed, on the other hand, then the scope of control structures is clearly visible at a glance. In fact, many conscientious programmers use indentations as a way of visually identifying control scopes even in languages that do not require them to. By requiring indentations, Python is able to ensure a more consistent coding style, which results in more-readable and compact code. Blender and Python assume that a tabbed indentation is equivalent to four spaces.

In addition to the high level of abstraction to simplify tasks and the advantages in readability enforced by the syntax, Python’s status as a full-fledged, object-oriented programming (OOP) language takes advantage of the OOP paradigm and the benefits that come with it. OOP enables programmers to define data structures that will be used in their programs, called classes. Individual instances of a class are called objects of that class. Much of OOP involves sending and receiving queries, called methods, between objects. Each class has specific methods defined for it. As a simple example, imagine a class called Person and another class called Car. A specific person is an object of class Person. It is reasonable to ask what color a person’s eyes are, so the question “What color are this person’s eyes?” is analogous to a method defined for Person. It doesn’t make sense to ask that question about a car, so that method would not be something that is defined for the class Car. The advantage of OOP is that after you understand the basics of the programming language, interacting with libraries that have been written by others requires only that you know what classes you are dealing with and what methods you should use with those classes to get the results you want. A full reference of classes, methods, and special variables for a given framework is called its application programming interface (API).

In the next two chapters, you will become familiar with Blender’s API, which will be your one-stop resource for information on accessing the classes you need to script for Blender. The ease with which libraries can be created and used leads to another important advantage of Python: the vast collection of libraries available. This allows for rapid prototyping of applications, without requiring you to write a lot of code.

Another reason why Python is the scripting language of choice for Blender is that Python is open-source software and can be incorporated and integrated into Blender to whatever degree is necessary without licensing issues. Python is not at all unique in this respect—many other scripting languages are also open-source—but combined with the other advantages of using Python, it makes Python the obvious choice as Blender’s scripting language.

Further Resources

The goal of this chapter is to give you the absolute bare minimum of Python knowledge that’s necessary to follow the discussion about scripting for Blender in the next few chapters. In the upcoming chapters, Blender-specific classes and functions will get most of the attention. For details about core Python functionality, you will need to turn to other resources outside this book. Even if you plan to use Python exclusively for Blender scripting, a more thorough understanding of the tools available to you in the Python language is invaluable.

Documentation, Books, and Tutorials

Official documentation for Python is available online at , as are downloads and installation information. In addition to the online documentation, a variety of books are available on Python, which address just about any conceivable question you might have. For a clear, leisurely introduction to the Python language, I recommend Learning Python, 4th Edition, by Mark Lutz (O’Reilly Media, 2009). It covers many of the introductory topics included in this book in much greater depth. For more-advanced subjects such as network programming, Mark Lutz’s Programming Python, 4th Edition (O’Reilly Media, 2011) is the definitive Python tome. If you have programming experience with other languages and would like to get a quick but well-presented overview of the ways in which Python implementations of common features differ from those in other languages, I recommend Dive Into Python 3 by Mark Pilgrim (CreateSpace, 2009), which has the additional benefit of being freely available online in a variety of convenient formats at . Python Cookbook by Alex Martelli, Anna Ravenscroft, and David Ascher (O’Reilly Media, 2005) is also a useful resource, filled with good “Pythonic” programming examples of common tasks.

The Blender-Python API

The Blender-Python API for Blender version 2.59 is located here:

If you plan to do Python scripting in Blender, you will want to bookmark this or even to download a local copy. A downloadable PDF version is available here:

This is the definitive reference for the classes, methods, and variables you will need to access Blender-related data in your scripts.

A few words of warning are in order. By taking on the challenge of Python scripting in Blender, you are, in a way, stepping into the “wild west” of Blender use. You are crossing over (if you haven’t already) to being a power user of Blender. The Blender-Python API has undergone major changes since the recode of the event system and interface that came with Blender 2.5, and the overhaul is not complete at the time of this writing, although it is quite close. As a power user and a budding Blender-Python programmer yourself, you will want to refer regularly to the latest API docs and keep yourself informed about developments.

You will certainly find an eager and knowledgeable community of users and developers online to help guide you through the wild patches. You can find support in the Python forum of BlenderArtists.org, located here:

For Python development, there are also the #blender, #blenderpython, and #blendercoders IRC channels.

Don’t be afraid to join the discussion and to point out areas where you think the API is lacking. The more people use this API and participate in its development and design, the faster improvements will come.


The Python Software Foundation
For the first several years after Python was initially developed by Guido van Rossum, the status of the Python intellectual property went through several changes as Guido worked under the auspices of various employers. By 2001, it was clear that Python had become too widely used for this to continue and needed a stable environment to thrive. The Python Software Foundation (PSF) was founded as a nonprofit corporation in the United States, with a mission to “promote, protect, and advance the Python programming language, and to support and facilitate the growth of the international community of Python programmers.” In practice, this involves maintaining and protecting trademarks and intellectual property associated with Python and supporting Python and Python-related development in a variety of ways. The PSF provides financial assistance for conferences as well as grants for Python-related training and development projects.
The PSF was patterned after other successful open-source software foundations, such as the Apache Software Foundation, which plays a similar role in promoting and supporting the widely used open-source Apache HTTP server and related software. In turn, the PSF was a predecessor in some respects of the Blender Foundation.
Companies with a stake in the development of Python contribute by becoming corporate sponsor members of the PSF. Sponsor members include ActiveState, Google, Microsoft, O’Reilly Media, and Sun Microsystems, among others. Industrial Light & Magic, the Hollywood special-effects powerhouse, is among the “emeritus” sponsor members of the PSF.
Although corporate sponsorship accounts for a considerable amount of the PSF’s revenue, the PSF’s status as a nonprofit organization enables (and depends on) contributions by individual community members as well. If you feel inclined to help contribute to the foundation, you can make a tax-deductable donation at .

Understanding the Python Development Environment

Any general-purpose book or tutorial you might read will assume that you have access to a command-line interface for your Python interpreter. Versions of Blender previous to 2.5 did not have their own interactive command-line interface, so it was a good idea to take the first steps in Python with a freestanding Python installation and use the native Python command-line environment (called IDLE) to get your bearings with the language. This is now resolved, and as previously mentioned, Blender incorporates a full Python interpreter and is entirely self-sufficient in terms of Python scripting. You can do all you need to do straight in Blender.

Using the Command-Line Shell

To get started, begin a new session of Blender. In one of your window areas, change the Editor Type menu to Python Console, as shown in . The Python Console window should look similar to the one shown in . Whenever it is opened, it will start by displaying a list of useful keyboard shortcuts as well as a command line you can type into.

Opening a Python Console window

c12f001.tif

The Python Console window’s command line

c12f002.tif

If you’ve used command-line interfaces such as on a Unix or Linux terminal or a DOS console, the idea of a command-line shell is already familiar. The command line enables you to directly write commands or requests (usually on a single line) and get an answer back, in this case directly from the Python interpreter. The line that begins with three greater-than symbols (>>>) is the command-line prompt (the last line in ). If you type your command on this line and press Enter, the Python interpreter’s reply will be printed on the next line, as shown here:

>>> print("Hello World!")  Hello World!  >>>

In this example, I requested that the Python interpreter print Hello World! As you can see, that’s exactly what it did.

As the command-line interface runs, the Python interpreter keeps track of the state it is in, which means that variables’ values can be assigned via the command line and then retrieved later, like this:

>>> my_variable = "Hello World!"  >>> print(my_variable)  Hello World!  >>>

This serves as a good example, but when you’re working directly in the command line, the print command is unnecessary. Simply entering a value in the command line will have the effect of echoing the value. Subsequent examples of working directly on the command line of the interpreter will omit the print command; however, it is still necessary to use print when writing code in scripts, so this won’t be the last you see of it.

Being able to interact with the command line also enables you to look more closely at the value of individual variables during runtime, which can be useful for debugging. For example, it might be of interest to investigate the data type of the variable assigned in the preceding code snippet. You can do this by using the type() function, which returns the data type of its argument. As you can see, the type returned is the str, which is the label for the string class:

>>> type(my_variable)  <class 'str'>

You’ll look more closely at data types later in this chapter. For now, it is enough to know that Python defines a set of basic data types that reflect the kind of data a variable represents. The string class treats data as sequences of characters. Because the original assignment of my_variable was a sequence of characters, it was automatically classified as an object of the string class. Different types can be accessed and dealt with in different ways. In the case of the str class, another thing you can ask about it is its length, as follows:

>>> len(my_variable)  12

Direct command-line access can be useful at times for certain things (for example, a bit later in this chapter, it will provide a convenient way to observe how data types interact).

Accessing the System Console

A very common and important use of the Python shell is as the default output and error report interface for running scripts. However, when you actually write complete scripts to be executed from the text editor or as add-ons, the output and error reports will not be sent to the interactive command line. Rather, you’ll see your scripts’ output in the System Console (different from the Python Console window.). When you run a script, this is where the print statements will print to by default, and when the script runs into trouble, this is where the errors will appear. The System Console interface is output only. Nevertheless, it remains indispensable for identifying errors.

To access the System Console on Windows, click Toggle System Console under Blender’s own Help menu, as shown in . The System Console in Windows is shown in .

Toggling the System Console in Windows

c12f003.tif

The System Console under Windows

c12f004.tif

The System Console equivalent in Mac OS X is the Terminal, and it can be accessed by executing Applications/Utilities/Terminal.app. It will return information from Blender only if Blender was opened via Terminal. To do this, right-click blender.app, choose Show Package Contents, and navigate to Contents/Mac0S/blender. This Unix executable file will open Blender, but unlike blender.app it will open via the Terminal, thus enabling the Terminal to return commands. For frequent Blender scripting, add this icon to your dock as a shortcut.

In Linux, the only system console available is the command-line terminal itself. To see the standard output and error messages from Blender, you need to execute Blender from the command-line terminal. Executing Blender from a terminal will also work in OS X.

Using the Text Editor

Generally, of course, programs are not executed one line at a time in a command-line environment. The norm is to write a script in a file and to execute that script by sending it to the interpreter (or calling it from within the interpreter, which amounts to the same thing). You can create a Python script with any ordinary text editor, but the simplest place to write Blender scripts is in Blender’s own text editor window.

Like all window types, the text editor is accessed through the Editor Type menu in the header of any window area. You can create a new file by clicking the New button in the header, as shown in .

Creating a new file in the Text Editor

c12f005.tif

The Blender text editor is a powerful editor with a variety of features for Python coding. For Blender Python programming, this will likely be your starting point and might be the only editor you ever need.

To see how easy it is to run a Python script from the text editor, type the line print("Hello World") into the text editor window. Run the code by pressing Alt+P or by clicking the Run Script button on the header. Check the Blender console to see the output.

You’ll use Blender’s Python Console a lot when you do Python scripting. It is where you will get most of the feedback you need for debugging, among other things.

Thus far in this chapter, you’ve learned enough about accessing the Python interpreter to get started with scripting. Now all you need to know is how to write Python code! The rest of this chapter is devoted to a quick overview of basic Python syntax.

Understanding Python Syntax

Python is similar to Perl and other scripting languages in that it has a procedural syntax that is augmented by object-oriented functionality. This means that Python programs execute in a step-by-step (procedural) way, using loops and conditionals, and accessing object data by using methods defined for classes. There are three fundamental things that you need to know in order to use Python: how individual units of data are represented and accessed, how the overall procedural flow of a program is determined, and how to work with classes and objects so you can understand and use an API such as the Blender-Python API.

Data Types and Structures

Python has several built-in basic data types. Each data type has its own way of interacting with operators and has specific ways in which its information can be accessed. In this section, you’ll learn about the most commonly used data types, which are the following:

Integers Integers (int) are numbers that can be represented without fractions or decimal points. Positive integers are sometimes referred to as natural numbers or counting numbers, but integers can also be negative. Integers are often used to iterate over lists or to identify unique entities.
Floating-Point Numbers Floating-point numbers (float) are numbers that include a decimal point. They behave as an approximation of real numbers and are the appropriate data type to use when you need to work with real numbers.
Boolean Values Boolean values (bool) are true or false values. They take the value True or False.
Strings Strings (str) are sequences of characters. When you want to work with words or text, str is the data type to use.
Lists Lists (list) are ordered collections of entities. The entities in lists can be of any other data type, and individuals can be accessed by an integer index. They can be added to and altered easily, making them appropriate when a dynamic ordered collection is needed.
Dictionaries Dictionaries (dict) are unordered collections of entities, in which pairs of entities have a key-value relationship. Values can be accessed via their corresponding keys.
Tuples Tuples (tup) are similar to lists but are limited in how they can be altered. They can be processed faster than lists, which makes them appropriate when an unchanging ordered collection is needed.

Lists, dictionaries, and tuples are particularly important data types because they contain other objects and enable access to them. Procedural control in Python almost always depends on manipulating these data structures. The following examples are best viewed in Blender’s Python Console.

Integers and Floating-Point Numbers

Integers and floating-point numbers (floats) are represented in Python by sequences of digits. Floats also contain a decimal point. Python can usually handle the interactions between integers and floating-point numbers in a natural and invisible way. For example, if you try to multiply an integer with a float, the answer will be the float that you intuitively expect.

Strings

Sequences of characters are appropriately handled as strings in Python. Of course, in a computer program everything is a sequence of characters, so it is necessary to identify strings by using single quotes or double quotes. Single or double quotes may be used interchangeably for strings in Python. If you have a string that contains single quotes, you can avoid the need to escape those quotes by using double quotes as your string delimiter. Sequences of characters that are not delimited by quotes are not treated as strings in Python. If the sequence is not a special function word in Python, the Python interpreter will try to treat the sequence as a variable. If this is not what you intended, chances are this will lead to an error.

There are numerous methods that can be called on strings. You can return the length of a string or individual characters by index similarly to the way you would a list, which you will see in the next section.

Lists and Tuples

Lists are represented in Python as ordered collections of entities within square brackets, where each entity is separated by a comma. An example of a list is shown here:

['a', 'b', 'c']

This list has three elements, the strings 'a', 'b', and 'c'. The len(list) function returns the length of the list, as shown here:

>>> len(['a','b','c'])  3

Elements of lists can be accessed by their individual indexes. List indexes start with 0 in Python, so the first element in the list is at index 0, and the last element of a list of length n is at index n-1. The notation for this is the index integer placed in square brackets immediately after the list. This notation is most commonly used when the list is stored in a variable, as you will see later in this chapter, but it can also be used with the list in plain notation, as shown here:

>>> ['a','b','c'][0]  'a'  >>> ['a','b','c'][1]  'b'  >>> ['a','b','c'][2]  'c'

Index access to lists in Python is very powerful. You can return not just individual elements but also slices or sublists, by indicating the start index and the index to which you want the sublist to extend (noninclusively). In this example, the [1:4] indexes are called, which returns the sublist extending from index 0 to index 3 of the original list:

>>> ['a','b','c','d','e'][1:4]  ['b', 'c', 'd']  >>>

Two important methods defined for lists are append() and extend(). Both add elements to lists. In some cases, these methods can be used interchangeably, but the way they are used is different. The first method, append(), adds a single element to a list. The append() method changes the list in place and does not, itself, output anything. To see how the list has changed, you need to pass it to a variable as follows so you can print the value after changing it:

>>> mylist = ['a','b','c']  >>> mylist.append('d')  >>> mylist  ['a', 'b', 'c', 'd']

The other common way to add elements to lists is to add the entire contents of another list to the first list, which is done using extend() as shown here:

>>> mylist = ['a','b','c']  >>> mylist.extend(['d','e','f'])  >>> mylist  ['a', 'b', 'c', 'd', 'e', 'f']

In this case, the argument for extend() is itself a list, and the resulting list is the concatenation of the original list with the contents of extend(). Note that if append() is called with a list as an argument, the effect is quite different:

>>> mylist = ['a','b','c']  >>> mylist.append(['d','e','f'])  >>> mylist  ['a', 'b', 'c', ['d', 'e', 'f']]

If append() is used with a list argument, the entire new list is appended as a single element in the original list. In this example, the new, post-append list has four elements, the last of which is itself a list.

Tuples are similar to lists in many respects. Instead of using square brackets, they are identified by round brackets. Their elements can be accessed by index similarly to the way lists can be. Tuples cannot be appended to or extended, and you cannot assign new values to individual items in tuples. For this reason, tuples are suitable only for collections that are fixed at the time of their creation.

Dictionaries

Whereas lists are collections of items that are ordered and accessible by an integer index, dictionaries are collections of items that are accessible via reference to other items. Dictionaries are represented by a comma-separated collection of pairs. The elements of the pairs are separated by colons, and the whole collection is within curly brackets, as in this example:

{'brit': 32, 'john': 25, 'mary': 29, 'tom': 74}

Each pair is called a key-value pair; the item to the left of the colon is the key, and the item to the right is its corresponding value. A value in a dictionary can be accessed by using its key, just as an element of a list is accessed by using its index:

>>> {'brit': 32, 'john': 25, 'mary': 29, 'tom': 74}['mary']  29

A list of all the keys in a dictionary can be output by using the keys() method, as shown here:

>>> {'brit': 32, 'john': 25, 'mary': 29, 'tom': 74}.keys()  ['tom', 'john', 'mary', 'brit']

Operators

Operators are the way a programming language determines the relationships between various data elements in a program. You’ve already seen an important operator, the = operator, or assignment operator. The purpose of this operator is to assign the value on the right of the operator to the variable on the left side of the operator. Be careful: Although this looks like an equal sign, it is not the sign used to indicate that two terms have the same value.

Python’s comparison operators are shown in .

Python’s Comparison Operators

OperatorValue
==Equal to
>=Greater than or equal to
>Greater than
<=Less than or equal to
<Less than
!=Not equal to

You can see the difference between assignment and equality with this example:

>>> a=5  >>> a  5  >>> a==5  True  >>> a==6  False

Furthermore, logical terms can be put together using either the and or or keyword.

Python has other operators also. It is important to realize when working with operators that they often have different meanings depending on the data type they are used with. Each data type listed in the previous section has different properties. One of the ways in which these data types differ is the way they behave with regard to operators. A good example of this is the + operator. If you use this operator between integers, as in this example, the predictable result is integer addition:

>>> 5+1  6  >>>

Using the + operator with floating-point numbers is similarly predictable. However, when working on strings, the meaning of the operator changes. In this case, the + operator becomes the string concatenation operator, as you can see in this example:

>>> "Hello " + "World!"'Hello World!'  >>>

If the + operator is used with lists, as in the following code, it has yet another meaning, namely list concatenation, which is to say the same meaning as extend():

>>> ['a','b','c']+['d','e','f']  ['a', 'b', 'c', 'd', 'e', 'f']

If you try to use the + operator with two data types for which it means different things, an error will arise, as in this case:

>>> "Hello World!" + 5  Traceback (most recent call last):    File "<blender_console>", line 1, in <module>  TypeError: Can't convert 'int' object to str implicitly

Another interesting example of operator behavior is the * operator. For integers and floats, it behaves as an ordinary multiplication operator. For strings and lists, however, it can be used with an integer to output a string or list consisting of the original string or list repeated the number of times indicated by the integer argument:

>>> "Hello" * 3  'HelloHelloHello'  >>> ['a','b','c'] * 3  ['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c']

Python is full of high-level tricks like this, and it is impossible for this book to do more than scratch the surface. This much knowledge of operators should be enough to get you going on scripting for Blender.

Variables

Python variables are represented as alphanumeric strings (without quotes, to distinguish them from actual Python strings). Unlike some languages such as Perl, in which variable names begin with specific characters to indicate their data type, variable names in Python can freely be used for any data type. In fact, the same variable can be assigned differently typed values one after another. You can check an item’s type by using the type() function. In the following example, the variable my_variable is initialized with a value of 10. When the type is checked, Python reports that the variable is an int. Then a new value of "Hello" is assigned to the variable and checked again to find that the variable is now of the string type:

>>> my_variable = 10  >>> type(my_variable)  <class 'int'>  >>> my_variable = "Hello!"  >>> type(my_variable)  <class 'str'>

Variables must be given a value before they can be accessed in any way, even in conditionals. Undefined variables in your code will result in a NameError in Python.

The difference between global and local variables will become clearer when the topic of defining functions is addressed. In short, variables that are initialized inside the definition of a function are local to that function, meaning that they cannot be accessed directly from outside the function in which they were defined. Global variables, on the other hand, are defined outside all functions and can be accessed from within any function. You’ll read more about this later in this chapter.

Control Flow

Control refers to the order in which a sequence of programming instructions is followed; repetition, iteration, and conditionality are all part of the control flow of a program. A core set of statements is used in Python to determine control flow. These include the for and if/else statements.


Indentation, not Brackets
One of the most immediately noticeable differences between Python and other common programming languages is the way it identifies control structures. Most languages do this with some kind of brackets. C, Perl, and Java, among others, use curly brackets to delimit control structures. Python, on the other hand, does not use brackets at all, but rather groups levels of embedding in control structures according to the left-side indentation of the code. This results in a visual immediacy for the code; control issues tend to pop out with Python code. However, it means that the interpreter is unforgiving with regard to white-space inconsistency. It also means that editing Python in more than one editor whose tab settings are different may result in errors. Some editors have features that enable you to visualize white space and distinguish between spaces and tabs. If you think you might be using more than one editor, be sure to check that the settings are consistent across editors.

The most common and simplest way to create a for loop is to iterate through a list, which is done like this:

>>> my_list = ['a','b','c']  >>> for item in my_list:  ...      print(item)  ...  a  b  c

To run this in the Python Console window, enter one line at a time of your code. Be sure to indent the content of the for loop. When you’ve entered the complete program (after the print(item) line) press Enter twice.

In this example a new variable, item, is initialized at the outset of the for loop. As the loop iterates through the list, this variable takes the value of each element of the list one by one. Note that there is no iteration on the index of the list items. In general, such explicit index iteration is not necessary. However, if you want to iterate over a numerical sequence, you can do so by using the range() function, which returns a list of integer values between two integer values (not inclusive of the second one), as shown here:

>>> for num in range(1,5):  ...     print(num)  ...  1  2  3  4

An optional third integer argument to range() can be used to set the step length of the range. The default is 1. If you want to count off by two or three, you can adjust the step length.

Conditionals are set by using if/elif/else statements. In this example, Python iterates through the numbers 0 to 9 with a step length of two. For each number, the interpreter checks to see whether the number is less than or equal to 2, greater than or equal to 8, or neither. The elif statement is Python’s else if conditional. Note particularly the left indentation. The if, elif, and else statements must all be aligned along the left side in order to correspond to each other. If the left indentation of those lines does not match, this code will result in an error.

>>> for num in range(0,10,2):            if num <= 2:                 print (str(num) + " is small")            elif num >= 8:                 print (str(num) + " is big")            else:                 print (str(num) + " is medium")  0 is small  2 is small  4 is medium  6 is medium  8 is big

A handy statement for programming is the pass statement. This statement is a placeholder that does nothing, but it can stand in for other code in a control structure when having no command would result in an indentation error.

Other control flow statements are available for use in Python, such as while and some modifications to the standard for loop. However, for the purposes of the content of the next few chapters, for loops and if/elif/else constructions will be sufficient to know about. For further information, please refer to the Python resources mentioned at the beginning of the chapter.

Functions

Much of programming in Python involves defining functions of your own, which can then be called elsewhere, including from within other functions. You can define a function on the command line with the def keyword like this:

>>> def my_simple_function():  ...    print("Hello World!")  ...

The Python interpreter will remember the definition, and you can call the function like this:

>>>   my_simple_function()

When you call the function, you will see that it outputs the words Hello World! just as if the print statement had been called directly. In fact, the print statement is being called from within the my_simple_function() function, which is defined using the def statement. Note also that as in the case of control structures, the content of a function definition is delimited not with brackets but by left indentation.

It is also possible to define functions that take arguments. To do this, a variable representing the argument is initialized in the function definition. When the function is called with a corresponding argument, the variable is instantiated with the argument value:

>>> def my_simple_function(arg):  ...     print ("Hello World" * arg)

The output of this script is the repetition of the string Hello World five times, as shown here:

>>> my_simple_function(5)  Hello WorldHello WorldHello WorldHello WorldHello World

Variables initialized inside a function are local to that function and cannot be accessed from outside that function. If you try to access a variable that has been defined inside a function outside that function, Python will give an error.

Variables initialized outside the function are global and can be accessed from within the function:

>>> my_global_variable = "Hello!"  >>>   def my_simple_function():  ...     print (my_global_variable)

Then call:

>>>   my_simple_function() 

This function will output the string Hello!. However, things get a bit more complicated when you want to change the value of global variables in the context of a function. In this next example, the variable my_global_variable begins with the value "Hello!" but is reassigned the value "World!" in the context of the function.

>>> my_global_variable = "Hello!"  >>> def my_local_function():  ...     my_global_variable = "World!"  ...     print (my_global_variable)

When you call the function, the output is printed "World!".

>>> my_local_function()  World!  >>> print (my_global_variable)  Hello!

Calling the function my_simple_function returns World! because within that function, my_global_variable is redefined as "World!". But if we then print my_global_variable outside the function, we see that it’s still globally defined as "Hello!".

To avoid this and to force changes made within the function to be applied to the global value of the variable, you need to use the global statement to declare the variable as a global variable within the function definition.

>>> my_global_variable = "Hello!"  >>>   def my_simple_function():   ...    global my_global_variable   ...    my_global_variable = "World!"   ...    print (my_global_variable)

If you add the global keyword to the variable, the function will change the global value of the variable, and you can check this by echoing the variable from the command line.

>>>   my_simple_function()  World!  >>> print (my_global_variable)  'World!'

Classes and OOP

Python is a fully object-oriented programming language, which means that data elements in the language are considered as instances of classes, which are defined to have attributes and methods. These instances of classes are called objects. Attributes refer to the kinds of data that the class has associated with it. For example, a class representing Person might have an attribute Eye Color. Methods are requests or messages defined for a specific class. A common type of method is one that returns an attribute value, so in this case a method for the class Person might answer the question “What is this person’s eye color?”

Defining your own classes is an important part of high-level programming in Python, particularly when programming complex systems. However, you can accomplish a great deal without having to define classes of your own, by using built-in classes and modules or libraries in which others have defined classes. For this reason, I will not go into depth about how to write class definitions here but rather focus on the basic syntax of objects, methods, and attributes, so when it comes time to look at the Blender API, you will be able to translate the information you find there into working Python code. A simple class definition for the class Person might begin something like this:

>>> class Person:  ...     eye_color = "Green"   ...    def get_eye_color(self):  ...         print(self.eye_color)

In this definition, there is only one attribute for a person, eye_color. There is also only one method defined, called get_eye_color(), which prints the value of the eye color variable.

As with built-in data types such as lists, strings, and integers, objects of defined classes can be passed to variables. Outside the class definition, it is possible to create an instance (object) of the Person class by assigning one to a variable, as shown here:

>>> p = Person()

After assigning the object to the variable p, you can access information from p by calling p.get_eye_color(). The syntax here is important. Calling a method on its object is done by appending the method name onto the end of the object name, separated by a dot. The method name ends with curly brackets containing whatever arguments are appropriate for the method. If no arguments are necessary, the brackets are empty. When this method is called for the first time, the string Green is printed out, because it is defined as the default value in the class definition.

>>> p.get_eye_color()  Green

Attribute values are also accessed by appending the value name to the end of the object name, separated by a dot. The next line assigns the string "Blue" to the eye_color attribute for p. After this new value is assigned to the attribute and p.get_eye_color() is called a second time, the string Blue is printed.

>>> p.eye_color = "Blue"  >>> p.get_eye_color()  Blue

In the API, you will find a large collection of descriptions of classes. Each class description also includes a description of the kinds of attributes and methods that are appropriate for interacting with objects of that class. After you get used to looking things up in the API, the information should become mostly self-explanatory most of the time. The next few chapters discuss some areas that might not be quite so obvious, to give you a sense of what kinds of inconsistencies to be on the lookout for. Becoming conversant with the way the API is intended to work will make it much quicker to get to the bottom of the problem on the occasions when things are not quite as they should be.

The dir() Function

A useful function that will save you tons of time looking things up in the API is dir(). By using this function with an object name as the argument, you can return a list of methods and attributes defined for the class of any object. Because in Python everything is an object, this means you can call dir() on any data you want to, even on methods themselves, and get a list of all the appropriate methods for that class. If you call dir() on the p variable representing a person from the previous section, a list will be returned like this:

>>> dir(p)  ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'eye_color', 'get_eye_color']

Most of the methods listed here are standard for all classes and hold various information about the module in which they are defined. The last two elements in the list are the attribute and method you defined previously: eye_color and get_eye_color, respectively.

Another useful source of information is the __doc__ attribute, which returns a documentation string when called from objects for which it’s been defined. Most built-in classes have defined __doc__ attributes. To see the documentation string for integers, try calling it from an int object, like this:

>>> a = 5  >>> a.__doc_

Modules

One of the main benefits of working in an OOP environment is that classes created by other people can be easily used by anyone who knows the API for the classes. It should not be necessary to see the actual code of the class definition in order to work with a class; all you should need is to know what attributes the object has, what methods are defined for the class, and what the methods return. In principle, you should be able to ignore everything else about how the classes and methods are specifically implemented.

To use classes defined by other people, you need to import the module in which the class is defined. Any Python script can be a module, and any class defined in a script can be imported into another script in this way. Modules are imported by using import modulename at the beginning of the script in which you want to use the imported classes. When this is done, classes from the module can be used, but it is necessary to preface calls to the class with the module name, as in modulename.classname. To use the class name without having to always append the module name, you must import the class from the module by using from modulename import classname. A common shortcut that can be used when the module does not contain an unwieldy number of classes is from modulename import *, which imports all classes from the module.

You will use this kind of construction a lot when working in the Blender-Python environment, because most of the classes you will be working with come from Blender-related modules enumerated in the API. In the next chapter, you will get familiar with the API and learn how to use it to access the information you need about your 3D assets in the Python environment.

The Bottom Line

Become familiar with the basics of the Python language. Python is a widely used language for scripting in many different application areas. It is known for its ease of use, readability, and speed of development.
Master It Make sure that you have a good reference handy for Python syntax. In this chapter, I listed several good books you should consider buying. Use a Google search to find some more good online resources to quickly look up Python operators and data types. Python has a number of great tools for working with data structures like strings, lists, and dictionaries. Read up on these, and learn how to work with list functions. What is the difference between the append() and extend() list functions? How can you reverse the ordering of a list?
Work with the Blender Python scripting environment. The simplest way to access Python directly is through the Python Console built into Blender. In this shell environment, you can execute individual commands and perform introspection on variables. Python can also be used by writing scripts in Blender’s text editor window and viewing the results in the System Console or Terminal.
Master It In this chapter, you learned that you cannot concatenate a string and an integer by using the + operator. Likewise, you cannot add a string numerically. In some cases, however, numerical data may be input (for example, in a form) as a string type. Study the references you searched for in the previous Master It exercise to learn about type casting in Python and find out how you would convert the string "5" into an integer that can be added to another.
Understand fundamental features of Python syntax. Python is a powerful programming language with a variety of data types, control structure options, and useful built-in functions. Its characteristic features include its reliance on indentation to represent logical structure.
Master It Create a variable my_list and assign it the list [1,2,1,3,1,4]. Call the dir() function with this list as an argument. Which of the methods returned by dir() do you think would be the correct method for removing one of the elements from the list? Experiment with the methods you think would work, and try to get rid of the number 2 from the list, so the list becomes [1,1,3,1,4]. Which method do you think will return the number of times the number 1 appears in the list? Additionally, how can you use .__doc__ strings to inquire about what you think the right answer is?

lookforrent
Буду знать! Оцените туристический портал lookfor.rent
JbnvJinge
12 month loans cash now cash loans in winchester tn cash advance in dubai
androidinfoSa
Знать достаточно свежие публикации у сфере планшетов и наблюдать презентации планшетов Андроид пользователи смогут на разработанном сайте запись телефонных звонков , который окажет помощь для Вас находиться в теме последних выпусков мировых марок в операционке Android и продажи задекларированной устройств. Популярный ресурс выдает потребителям совершенно популярные предметы обсуждения: мнение экспертов про телефоны, оценка пользователей, обновление, апки для персональному смартфону, ОС Андроид, ответы на популярные вопросы также различные основные содержание, какими интересуются регулярно. Стоит коротко увидеть новый телефон и выделить уникальные характеристики? Вовсе не AndroidInfo.Ru преград - у основной строчке возможно кликнуть модель либо ключевое слово затем одержать с вашего задания подходящую параграф совместно с фотоотчетом плюс описанием преобладающего функций. В случае если юзер есть несомненного ценителя выпусков смарт устройств по операционке Андроид Android , здесь регистрация поможет юзерам ни разу не выпустить каждую единую добавленную новость у области умных систем. Будет изобилие всего увлекательного также развивающего для всем ценителей инноваций новой эры.
Anciwhish
buying paper custom written papers
DbgvAmurn
dissertation research research methodology dissertation

© RuTLib.com 2015-2018