python之7-1類

  • 面向對象的編程,實際上是將對象抽象成類,而後在類中,經過init定義實例初始化函數和多個操做實例的函數.python

  • 整個類就如同一個模板,咱們能夠用這個模板生成衆多具現實例,並賦予實例動做.編程

  • py中定義類的大體格式以下:函數

class 類名():
類變量名 =
類名.類變量名    #調用類變量
    def _init_(self,參數1,參數2):   #這裏的參數也能夠沒有,便可以直接 self.屬性 = 值  而self每次對應的就是實例本身
        self.屬性1 = 參數1
        self.屬性2 = 參數2
    def 實例方法函數名(self,方法變量1,方法變量2):   
        函數體

實例名 = 類名(參數1,參數2)    #實例建立
實例名.實例方法函數名()    #實例動做函數調用
  • 註釋1:self這裏就是實例統稱,屬性1和屬性2是類的屬性,而後將屬性1和屬性2得到的參數傳遞給實例,構建實例的屬性,最後這些實例屬性,被方法函數所調用oop

  • 註釋2:this

類 就像是 包;spa

init函數 就如同包裏面的 init模塊 ,來介紹這個類;對象

方法函數 就像是包裏面的 其餘模塊,來具體實現類的操做it

  • 例子1:
#!/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()
  • 例子2:獲取一組連續數字的中間數字
#!/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()
相關文章
相關標籤/搜索