免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 5783 | 回复: 0
打印 上一主题 下一主题

python class [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2010-02-19 23:19 |只看该作者 |倒序浏览
#!/usr/local/bin/python$
class Person:$
    population=0$
    def __init__(self,name):$
        self.name=name$
        Person.population+=1$
    def sayHi(self):$
        print "Hello,how are you? my name is ", self.name$
    def __del__(self):$
        print "%s say bye." %(self.name)$
        Person.population-=1$
        if Person.population==0:$
           print 'I am the last one.'$
        else :           $
            print "there are still %d people left." % Person.population$
    def howMany(self):$
        if  Person.population==1:$
           print 'I am the only person here.'$
        else :$
            print "we  have  %d people here." % Person.population$
###$
p1=Person('taohx')$
print p1$
p1.sayHi()$
p1.howMany()$
#$
p2=Person('m2')$
print p2$
p2.sayHi()$
p2.howMany()$

示例2:###
#!/usr/bin/python
# Filename: inherit.py
class SchoolMember:
    '''Represents any school member.'''
    def __init__(self, name, age):
        self.name = name
        self.age = age
        print '(Initialized SchoolMember: %s)' % self.name
    def tell(self):
        '''Tell my details.'''
        print 'Name:"%s" Age:"%s"' % (self.name, self.age),
class Teacher(SchoolMember):
    '''Represents a teacher.'''
    def __init__(self, name, age, salary):
        SchoolMember.__init__(self, name, age)
        self.salary = salary
        print '(Initialized Teacher: %s)' % self.name
    def tell(self):
        SchoolMember.tell(self)
        print 'Salary: "%d"' % self.salary
class Student(SchoolMember):
    '''Represents a student.'''
    def __init__(self, name, age, marks):
        SchoolMember.__init__(self, name, age)
        self.marks = marks
        print '(Initialized Student: %s)' % self.name
    def tell(self):
        SchoolMember.tell(self)
        print 'Marks: "%d"' % self.marks
t = Teacher('Mrs. Shrividya', 40, 30000)
s = Student('Swaroop', 22, 75)
print # prints a blank line
members = [t, s]
for member in members:
    member.tell() # works for both Teachers and Students


本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u3/107145/showart_2182579.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP