ca-class-simple

Übersicht: Python & Blender


Objectives

Classes are part of a programming paradigma. We use Python which is a object oriented programming language. With this knowledge it is possible to build and add new functionality to Blender and your projects. Let's see how it works.

Instructions

Tasks:
  1. Read the text about objectoriented programming on wikipedia.
  2. Build and test the class shown in this station.
  3. Replace the text with your own.
  4. Mix the concept of a class with positioning a Text in the 3D-View (Text in 3D <text_in_3d_view>).

Simple class

This example is taken from: Blender API.

The code:

blender-extended/simple_class.py (Source)

import bpy


class HelloWorldOperator(bpy.types.Operator):
    bl_idname = "wm.hello_world"
    bl_label = "Minimal Operator"

    def execute(self, context):
        print("Hello World")
        return {'FINISHED'}

bpy.utils.register_class(HelloWorldOperator)

# test call to the newly defined operator
bpy.ops.wm.hello_world()

Notes about the code (step by step)

A class definition is introduced by the keyword class, followed by a self-selected name and finally a pair of parentheses. As in our case, the class can also inherit properties of another class, in our example bpy.types.Operator. A colon marks the start of the block, the next line(s) must be indented.

blender-extended/simple_class.py (Source)

class HelloWorldOperator(bpy.types.Operator):

Two variables are defined that. This ist necessary for the integration of our class in the Blender system.

blender-extended/simple_class.py (Source)

    bl_idname = "wm.hello_world"
    bl_label = "Minimal Operator"

No class without methods. A method is introduced by the keyword def and the first parameter used, is self. With self the connection between function and class is defined. In our example, the second parameter context is mandatory and used by Blender. The function does not really do much. Finally a typical blender statement, gives the value {'FINISHED'} back.

blender-extended/simple_class.py (Source)

    def execute(self, context):
        print("Hello World")
        return {'FINISHED'}

Finally, the new class is registered in the Blender system and also a trial statement is called. The result can be seen in the console. There, the Hello World should be printed as expected (Don't forget to start Blender from a console window).

blender-extended/simple_class.py (Source)

bpy.utils.register_class(HelloWorldOperator)

# test call to the newly defined operator
bpy.ops.wm.hello_world()

Comments