Graphics Reference
In-Depth Information
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,
youneedtousethe global statementtodeclarethevariableasaglobalvariablewithinthefunctiondefinition.
>>> 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 pro-
grammingcomplexsystems.However,youcanaccomplishagreatdealwithouthavingtodefineclassesofyour
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 in-
formationyoufindthereintoworkingPythoncode.Asimpleclassdefinitionfortheclass Person mightbegin
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.
Aswithbuilt-indatatypessuchaslists,strings,andintegers,objectsofdefinedclassescanbepassedtovari-
ables. 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:
Search WWH ::




Custom Search