python之7-1类

时间:2014-07-17 18:06:13   收藏:0   阅读:355
class 类名():
类变量名 =
类名.类变量名    #调用类变量
    def _init_(self,参数1,参数2):   #这里的参数也可以没有,即可以直接 self.属性 = 值  而self每次对应的就是实例自己
        self.属性1 = 参数1
        self.属性2 = 参数2
    def 实例方法函数名(self,方法变量1,方法变量2):   
        函数体

实例名 = 类名(参数1,参数2)    #实例创建
实例名.实例方法函数名()    #实例动作函数调用

类 就像是 包;

init函数 就如同包里面的 init模块 ,来介绍这个类;

方法函数 就像是包里面的 其他模块,来具体实现类的操作

#!/usr/bin/python
# Filename: objvar.py

class Person:
    ‘‘‘Represents a person.‘‘‘
    population = 0

    def __init__(self, name):
        ‘‘‘Initializes the person‘s data.‘‘‘
        self.name = name
        print ‘(Initializing %s)‘ % self.name

        # When this person is created, he/she
        # adds to the population
        Person.population += 1

    def __del__(self):
        ‘‘‘I am dying.‘‘‘
        print %s says 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 sayHi(self):
        ‘‘‘Greeting by the person.

        Really, that‘s all it does.‘‘‘
        print ‘Hi, my name is %s.‘ % self.name

    def howMany(self):
        ‘‘‘Prints the current population.‘‘‘
        if Person.population == 1:
            print ‘I am the only person here.‘
        else:
            print ‘We have %d persons here.‘ % Person.population

swaroop = Person(‘Swaroop‘)
swaroop.sayHi()
swaroop.howMany()

kalam = Person(‘Abdul Kalam‘)
kalam.sayHi()
kalam.howMany()

swaroop.sayHi()
swaroop.howMany()
#!/usr/bin/python2.6
class lis:
    def __init__(self, start, end):
        self.start = start
        self.end = end
    def test(self):
        if ( self.start % 2 == 0 and self.end % 2 == 0 ) or ( self.start % 2 == 1 and self.end % 2 == 1):
            print ( self.start + self.end ) / 2
        elif self.start % 2 == 1 or self.end % 2 == 1:
            tmp_num = ( self.start + self.end + 1) / 2
            print tmp_num - 1, tmp_num

a = lis(1,10)
b = lis(1,9)
c = lis(2,10)
d = lis(2,9)
a.test()
b.test()
c.test()
d.test()

python之7-1类,布布扣,bubuko.com

原文:http://www.cnblogs.com/aaa103439/p/3851304.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!