Python Tools — Session 7A

Slicing, Extruding Faces, Intro to Classes

2020.02.18 — Session 7A

Session Navigation

Overview

This session is a comprehensive tutorial that starts with Python list and string slicing operations, then applies slicing to extrude every other face on a sphere in Maya. It finishes with foundational class concepts including the self keyword, instance creation, method definitions, and the __init__ constructor.

Key Concepts

  • List Slicing — Using [start:end:step] syntax to extract sublists, including negative indexing and step values
  • String Slicing — Treating strings as character lists for extraction and reversal operations
  • Face Extrusion — Selecting every other face using slicing and applying polyExtrudeFacet operations
  • Classes and self — Organizing code into classes where self provides shared state across methods
  • __init__ Constructor — Initializing class instances with parameters using the special __init__ method
  • List Sorting — Using sort() and reverse() to order list elements

Code

notes.py — List Slicing, Face Extrusion, String Slicing, and Intro to Classes

"""
#############################################################################
filename    session_7a.py
author      Matt Osbond 
dP email    m.osbond@digipen.edu
course      CS115
Brief Description:
    Session 7A - Tuesday Feb 18th 2020
    Exploring slicing of lists and strings, and intro to classes
#############################################################################
"""

# LIST SLICING

numbers = [0, 1, 2, 3, 4]
#          0  1  2  3  4
#         -5 -4 -3 -2 -1

          
# Printing the whole thing
print numbers
## [0, 1, 2, 3, 4]

# Accessing element index 3 (this is the 4th element, as the indices start at 0 !!)
print numbers[3]
## 3

# Using a negative, we tell python tht we want to start from the end work backwards
# Note that when going in backwards direction, you DO NOT start at 0
print numbers [-2]
## 3

# Slicing is denoted by the colon ":" symbol
# The left hand side is the amount of elements to slice off from the left
# The right hand side is the amount of elements to slice off from the right, working backwards
# When a side is left blank, it will keep everything in that direction
print numbers [:]
##[0, 1, 2, 3, 4]

# Lets slice off the first and last elements
# NOTE this count is NOT the same as index. The "1" on the left means "remove one element"
# not "remove up to element 1" as this would remove two elements
print numbers [1:-1]
## [1, 2, 3]

# You can add a second colon, and the number in the thrid space s the "step" by which to count
# Starting from 0, we get all the even numbers
print numbers[::2]
## [0, 2, 4]

# Combining these together and slicing off the first element lets us get the odd numbers
print numbers[1::2]
## [1, 3]

# SLICING FACE LISTS

""" 
Small project to showcase a real example of extruding every other face on a sphere using list slicing
"""

import pymel.core as pm

# Create a slightly lower res sphere
ball = pm.polySphere(sx = 10, sy = 10)[0]

# Slicing: ball.faces[::2]
# By leaving the first two bits blank...
#.. we start from the beginning and end at the end
# The third bit is the step. We want every other one, so we set this to 2
for face in ball.faces[::2]:

    # Enable extrusion on this face, and capture the extrude object
    ex = pm.polyExtrudeFacet(face)[0]

    # Create an attribute string to set
    # These always have to be "OBJECT.ATTRIBUTE"
    attr = ex + '.localTranslate'

    # Extrude the face by setting the attribute
    pm.setAttr(attr, (0,0,1))

# STRING SLICING
"""
Showing how strings are essentially a "list of characters" in Python
"""

url = 'http://google.com'

# Just print everything
print url
## http://google.com

# Strip off the "http://" (7 characters)
# Strip off the ".com" (4 characters)
print url[7:-4]
## google

# By using a negative step, we can go backwards
print url[::-1]
## moc.elgoog//:ptth

# SORTING LISTS

numbers = [0, 5, 2, 4, 1, ]

# Print everything
print numbers
# [0, 5, 2, 4, 1]

# Sort the list ascending numerically
numbers.sort()
print numbers
# [0, 1, 2, 4, 5]

# Reverse it now it's sorted
numbers.reverse()
print numbers
# [5, 4, 2, 1, 0]

###########################################

CLASSES

"""
Why use clases? We frequently want toa ccess variables across functions. Classes are one of the cleanest way to do so.
For example, this will yield an error:
"""

def do_stuff():
    a = 'some stuff I made'

    
do_stuff()

def add_stuff():
    a = a + ' some more stuff'
    print a

    
add_stuff()

# # Error: UnboundLocalError: file <maya console> line 8: local variable 'a' referenced before assignment # 

# Re-writing this using a class, we get:

class Stuff():
    # Note here the use of "self". self is ALWAYS the first argument in ANY method in you class you want to be accessible
    def do_stuff(self):
        self.a = 'some stuff I made'

    def add_stuff(self):
        self.a += ' some more stuff'

# With classes, you have to create an instance
my_instance = Stuff()

# Run your first method and print the value of "a"
my_instance.do_stuff()
print my_instance.a

# Run your second method and print the value of "a"
my_instance.add_stuff()
print my_instance.a


####################################################


class Student:
    """a base student class
    """
    def __init__(self, _name, _course):
        """Initialize with first and last name"""
        self.name = _name
        self.course = _course


    def get_name(self):
        """Query the name of the current instance"""
        print self.name

# Create an instance of the Student class, initializing it with the student name and the course name
s1 = Student('Henry Ford', 'Cars')

# Run the method that prints the student's name
s1.get_name()
← Prev Next →