dreamsys software

Python Scripting Tutorial

Enums

An Enum, or enumeration, is a list of constant values. Many programming languages have this concept and as of Python 3.4, so does python. But don't worry if you have a version of python prior to 3.4, you can still use enums, you just have to define them differently.

Let's say you have a User class and it has a property "gender", you want the user to specify one of three values: male, female or unspecified. We can make the gender property an enum.

#!/usr/bin/env python

from enum import Enum
class Gender(Enum):
	MALE = 0
	FEMALE = 1
	UNSPECIFIED = 2

class User:
	name = ""
	age = 0
	gender = Gender.UNSPECIFIED

	def display(self):
		if (self.gender == Gender.MALE):
			print self.name, 'is a male'
		elif (self.gender == Gender.FEMALE):
			print self.name, 'is a female'
		else:
			print self.name, 'did not specify a gender'

user1 = User()
user1.name = 'Mike'
user1.gender = Gender.MALE

user2 = User()
user2.name = 'Sally'
user2.gender = Gender.FEMALE

user1.display()

This will only work if you have Python 3.4 or later, if not, use the below script.

#!/usr/bin/env python
def enum(**enums):
	return type('Enum', (), enums)

Gender = enum(MALE=0, FEMALE=1, UNSPECIFIED=2)

class User:
	name = ""
	age = 0
	gender = Gender.UNSPECIFIED

	def display(self):
		if (self.gender == Gender.MALE):
			print self.name, 'is a male'
		elif (self.gender == Gender.FEMALE):
			print self.name, 'is a female'
		else:
			print self.name, 'did not specify a gender'

user1 = User()
user1.name = 'Mike'
user1.gender = Gender.MALE

user2 = User()
user2.name = 'Sally'
user2.gender = Gender.FEMALE

user1.display()
user2.display()

In the next section we will learn how to integrate with the shell.

Prev (Lists & Maps) | Next (REST Service)


Blog Entries
Blob Entry 1
Blob Entry 2
Blob Entry 3
Blob Entry 4
Blob Entry 5
Blob Entry 6