Table of Contents

About

Object - Class (or Struct) in Python

The difference with a standard class implementation is that in Python, Classes are objects because the class keyword will creates an object. Only a class object is capable of creating objects.

Creation

Class keyword

A basic class consists only of the class keyword, the name of the class, and the class from which the new class inherits in parentheses.

By convention, user-defined Python class names start with a capital letter.

Accessing attributes of our objects is made using dot notation.

class Fruit(object):
	"""A class that makes various tasty fruits."""
        
        # Member variable
        myBoolean = True

        # The init function is used to initialize the objects (required)
        # The self argument refers to the object being created.
        # It's common to use self as the first parameter 
	def __init__(self, name, color, flavor, poisonous):
		self.name = name
		self.color = color
		self.flavor = flavor
		self.poisonous = poisonous
	
	def description(self):
		print "I'm a %s %s and I taste %s." % (self.color, self.name, self.flavor)
		
	def is_edible(self):
		if not self.poisonous:
			print "Yep! I'm edible."
		else:
			print "Don't eat me! I am super poisonous."

lemon = Fruit("lemon", "yellow", "sour", False)

lemon.description()
lemon.is_edible()

Dynamic

With the type function, you can create class dynamically, see Python Type - Dynamic Class.

Factory

Because a class is an object, you can manipulate it as any variable.

def class_factory(name):
	if name == 'foo':
		 class Foo(object):
			 pass
		 return Foo # return the class, not an instance
	else:
		 class Bar(object):
			 pass
		 return Bar

Properties

Class

the __class__ attribute

Name

The name of the class is in the __name__ attribute.

If you have a nested package named foo.bar with a class Myclass, the method myMethod on that class will have:

  • as name: myMethod
  • as fully qualified name: foo.bar.Myclass.myMethod

See also:

  • PEP 3155, Qualified name for classes and functions.

Import

A qualified name lets you re-import the exact same object, provided it is not an object that is private to a local (function) namespace.

Call

When calling the items method

my_dict.items()

Python checks to see if the dictionary my_dict has an items() method and executes that method if it finds it.

Inheritance

See Python - Class Inheritance

Method

Static

@staticmethod
def staticMethod(par1, par2):

Class

@classmethod
def classMethod(par1, par2):

Add a method

def echo(self):
          print('foo')
          
MyClass.echo = echo
hasattr(MyClass, 'echo')
True

Type

print(type(myClass))
<type 'type'>

Attribute

Accessing attributes of our objects is made using dot notation.

hasattr(ClassName, 'attribute_name')

Modification

You can change classes by using two different techniques: