#coding=utf8
'''
Created on 2011-6-12
@author: hufei
'''
name = 'hufei'
if not name:
pass
else:
class Person: # class can be defined in a branch of 'if' statement
def __init__(self,name,age):
self.name = name
self.age = age
def __str__(self):
return u"%s:%d" % (self.name, self.age)
def say_hello(self):
print 'Hello'
def say_hi(name):
print u"%s:hi" % name
def say_hello(name):
print u"%s: hello!" % name
maimai = Person('maimai',22)
#attributes need not be declared, they spring into existence when they are first assigned
maimai.sex = 'Female'
print maimai #invoke __str__
print maimai.sex
print type(maimai.age)
print type(maimai.say_hello) #
maimai.say_hello = say_hi # methodname just looks like a reference, can be modified
maimai.say_hello('Jack')
maimai.say_hi = say_hello # method of Class can be added dynamically
maimai.say_hi('Tom')
python中的类的语法与java相比,灵活多变。相比而言,java是严格而规范的语言,而python给人更加随意的感觉。
分享到:
2011-06-12 23:11
浏览 457
评论