#!/usr/bin/env python
class MyClass( object):
"""
A simple example class
"""
#
# i is a class variable
#
i = 1
#
# the constructor
#
def __init__( self):
print( " __init__")
self.data = []
#
# this is how to deal with errors in the constructor
#
if someThingIsWrong:
raise Exception( "MyClass", "something is wrong")
#
# __del__() is called by the garbage collector, not
# when the last reference to an object is lost, e.g.
# by executing 'del obj'.
# !!! do not use __del__() !!!
#
def __del__( self):
print( " __del__")
def f( self):
MyClass.i += 1
return 'hello world'
x = MyClass();
# -> __init__
print( "%s" % x.f())
# -> hello world
print( " i %d" % MyClass.i)
# -> i 2
# -> __del__
Data members need not to be declared. We can start with an empty class:
#!/usr/bin/env python
class Employee(object):
pass
john = Employee() # Create an empty employee record
# Fill the fields of the record
john.name = 'John Doe'
john.dept = 'computer lab'
john.salary = 1000
print( john.name)