Python - Class

1 - 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.

3 - Creation

3.1 - 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): = 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.flavor)
	def is_edible(self):
		if not self.poisonous:
			print "Yep! I'm edible."
			print "Don't eat me! I am super poisonous."

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


3.2 - Dynamic

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

3.3 - Factory

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

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

3.4 - Properties

3.5 - Class

the __class__ attribute

3.6 - Name

The name of the class is in the __name__ attribute.

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

  • as name: myMethod
  • as fully qualified name:

See also:

  • PEP 3155, Qualified name for classes and functions.

4 - 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.

5 - Call

When calling the items method


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

6 - Inheritance

7 - Method

7.1 - Static

def staticMethod(par1, par2):

7.2 - Class

def classMethod(par1, par2):

7.3 - Add a method

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


8 - Type


<type 'type'>

9 - Attribute

Accessing attributes of our objects is made using dot notation.

hasattr(ClassName, 'attribute_name')

10 - Modification

You can change classes by using two different techniques:

Data Science
Data Analysis
Data Science
Linear Algebra Mathematics

Powered by ComboStrap