class className:
method
variable
obj = className() # declaer a objection
类变量与对象变量其作用范围有所不同,类变量为该类所有对象共有,对象变量只为该对象共有,类变量与类中的方法是并列关系,对象变量在初始化对象的时候指明。
程序
class dog:
count = 0 #declear a global variable 'count'
def __init__(self,name,count): #a objection has two objection variables 'name' and 'count'
self.name = name
self.count = count+1
dog.count = dog.count+1
def __del__(self):
print '''I'm %s, bye''' % self.name
def howMany(self):
print '''I'm %s, the count of dog is %d''' % (self.name,dog.count)
toy=dog('toy',0)
toy.howMany()
print 'count%d'%toy.count
kerian=dog('kerian',0)
kerian.howMany()
print 'count:%d' % kerian.count
I'm toy, the count of dog is 1
count:1
I'm kerian, the count of dog is 2
count:1
I'm kerian, bye
I'm toy, bye
class B(A):
...
...
class Person():
def __init__(self,name,age):
self.name=name
self.age=age
def __del__(self):
print '''I'm %s,bye''' % self.name
def tell(self):
print '''My name is %s, I'm %d years old''' % (self.name,self.age),
class Student(Person):
def __init__(self,name,age,mark):
Person.__init__(self,name,age)
self.mark = mark
def tell(self):
Person.tell(self)
print 'My mark is %d' % self.mark
S = Student('kerian',18,100)
S.tell()
My name is kerian, I'm 18 years old My mark is 100
I'm kerian,bye
class ShortInputException(Exception):
'''this class inherits from Exception class'''
def __init__(self,length,atleast):
Exception.__init__(self) # initialize the class
self.length=length
self.atleast=atleast
try:
s = raw_input('Enter->>') #input a string
if len(s) < 3:
x = ShortInputException(len(s),3) # create a object
raise x #raise a exception
except EOFError: # input a unexpected end
print '\nWhy did you do an EOF on me?'
except ShortInputException: #raise a exception because the length of input strin
g less atleast
print 'ShortInputException: the at least of input length is %d' % x.atleast
else:
print 'No exception was raised'
Enter->>ab
ShortInputException: the at least of input length is 3
Enter->>abc
No exception was raised
class ShortInputException(Exception):
'''this class inherits from Exception class'''
def __init__(self,length,atleast):
Exception.__init__(self) # initialize the class
self.length=length
self.atleast=atleast
try:
s = raw_input('Enter->>') #input a string
if len(s) < 3:
x = ShortInputException(len(s),3) # create a object
raise x #raise a exception
except EOFError: # input a unexpected end
print '\nWhy did you do an EOF on me?'
except ShortInputException: #raise a exception because the length of input string less atleast
print 'the atleast of length is %d' % x.atleast
finally:
print 'input is %s' % s
Enter->>a
the atleast of length is 3
input is a
Enter->>adc
input is adc