類與對象的方法

來源:互聯網
上載者:User

類與對象的方法

我們已經討論了類與對象的功能部分,現在我們來看一下它的資料部分。事實上,它們只是與類和對象的名稱空間 綁定 的普通變數,即這些名稱只在這些類與對象的前提下有效。

有兩種類型的 域 ——類的變數和對象的變數,它們根據是類還是對象 擁有 這個變數而區分。

類的變數 由一個類的所有對象(執行個體)共用使用。只有一個類變數的拷貝,所以當某個對象對類的變數做了改動的時候,這個改動會反映到所有其他的執行個體上。

對象的變數 由類的每個對象/執行個體擁有。因此每個對象有自己對這個域的一份拷貝,即它們不是共用的,在同一個類的不同執行個體中,雖然對象的變數有相同的名稱,但是是互不相關的。通過一個例子會使這個易於理解。

使用類與對象的變數#Filename:objvar.py
class Person:
    population=0
    def __init__(self,name):
        self.name=name
        print ("initializing %s") % self.name
        Person.population+=1
    def sayHi(self):
        print ("Hi,my name is %s") % self.name
        print ('there are %d people in the world' % Person.population)
    def __del__(self):
        print "%s says goodbye" % self.name
        Person.population-=1
        if(Person.population==0):
            print 'no one in the world'
        else:
            print "There are still %d people left" % Person.population
        

a1=Person("shanshan");
a1.sayHi()

a2=Person("siliang")
a2.sayHi()

del a1
del a2

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.