How to define class in Python

What Is a Class?

A class is a kind of object. All objects belong to one class and are said to be instances of that class. For example, a bird is an instance of the class Bird.

The following code shows how to create a class in Python.


class Person: # ww  w .ja  v  a 2 s . co  m
    def setName(self, name): 
        self.name = name 
    def getName(self): 
        return self.name 
    def greet(self): 
        print "Hello, world! I'm %s." % self.name 

foo = Person() 
bar = Person() 
foo.setName('Java') 
bar.setName('Python') 
foo.greet() 
bar.greet() 
# The attributes are also accessible from the outside: 
print foo.name 

The code above generates the following result.

This example contains three method definitions. Person is the name of the class.

The class statement creates its own namespace where the functions are defined. self parameter refers to the object itself. When setName is called, foo itself is automatically passed as the first parameter.

Special Class Attributes

NameMeaning
C.__name__ String name of class C
C.__doc__ Documentation string for class C
C.__bases__ Tuple of class C's parent classes
C.__dict__ Attributes of C
C.__module__ Module where C is defined (new in 1.5)
C.__class__ Class of which C is an instance (new-style classes only)

class MyClass: # from w ww. j  a v a2s. com
   pass



print MyClass.__name__
print MyClass.__doc__
print MyClass.__bases__
print MyClass.__dict__
print MyClass.__module__

The code above generates the following result.





















Home »
  Python »
    Language Basics »




Python Basics
Operator
Statements
Function Definition
Class
Buildin Functions
Buildin Modules