Python對象和類

來源:互聯網
上載者:User

標籤:定義   call   code   存在   基類   most   oss   注意   ret   

Python 裡的所有資料都是以對象形式存在的,對象是類的執行個體。

定義類(class)

使用class來定義一個類。

比如,定義一個cat類,如下:

class Cat():
  def __init__(self):   self.name = name

建立兩個cat類的執行個體cat1,cat2,如下:

cat1 = Cat(‘mimi‘)cat2 = Cat(‘momo‘)

類中的__init__為初始化函數,在執行個體建立的時候執行。它的第一個參數必須是self.

 

繼承

一個類可以繼承另一個類,被繼承的類可以稱為‘父類‘或者‘基類‘。使用繼承得到的新類會自動獲得舊類中的所有方法,而不需要進行任何複製。在新類中,可以定義新的方法,也可以對繼承的方法修改,修改後會覆蓋原有的方法。

在python中,所有的類都繼承了object類。

下面是一個簡單的類繼承的例子。

class Cat():  def __init__(self):      self.name = name
  def play():
    print("I like play")
class BossCat(Cat): def play(ball):
    print("I like play %s", %ball)

BossCat的play方法覆蓋了Cat類的play方法,所以,這兩個類各自的對象執行play時會有不一樣的表現。

 

使用super方法

子類中的__init__()方法(如果定義)會覆蓋父類中__init__()。如果子類的__init__()方法要繼承父類的__init__()方法的參數就可以使用super方法,如下:

>>> class Person():    def __init__(self,name):        self.name = name        >>> class EmailPerson(Person):    def __init__(self,name,email):        super().__init__(name)        self.email = email

 

屬性的訪問和設定

python中所有特性都是公開的,如果想要在類中實現一些私人屬性的話,可以:

1 getter 方法和setter 方法

比如:

>>> class Person(object):    def __init__(self,name,age):        self.name = name        self.age = age    def get_name(self):        return self.name    def set_name(self,name):        self.name = name        >>> perter= Person(‘peter‘,28)>>> perter.name‘peter‘>>> perter.name = ‘perter‘>>> perter.name‘perter‘>>> 

 

2 使用@property擷取屬性, @xxx.setter來設定屬性值。

比如:

class Student(object):    @property    def birth(self):        return self._birth    @birth.setter    def birth(self, value):        self._birth = value    @property    def age(self):        return 2014 - self._birth>>> S1 = Student()>>> S1.birth = 1989>>> S1.birth1989>>> S1.age25>>> S1.birth = 1990>>> S1.birth1990>>> S1.age24>>> S1.age = 26Traceback (most recent call last):  File "<pyshell#15>", line 1, in <module>    S1.age = 26AttributeError: can‘t set attribute

3 使用‘__‘來定義內部私人/隱藏的屬性。

如下:直接存取__定義的屬性時會報錯。

>>> class Person(object):    def __init__(self,input_name,age):        self.__name = input_name        self.__age = age    @property    def name(self):        return self.__name    @name.setter    def name(self,input_name):        self.__name = input_name        >>> Peter = Person(‘Peter‘,29)>>> Peter.name‘Peter‘>>> Peter.__nameTraceback (most recent call last):  File "<pyshell#24>", line 1, in <module>    Peter.__nameAttributeError: ‘Person‘ object has no attribute ‘__name‘

 

 

執行個體方法/類方法/靜態方法

執行個體方法(instance method): 以self作為第一個參數的方法。當調用方法時,python會將調用該方法的對象作為self參數傳入。

類方法(class method):使用@classmethod修飾的方法。注意,類方法的第一個參數是類本身cls。

>>> class TeamA():    num = 0    def __init__(self):        TeamA.num += 1            @classmethod    def counter(cls):        print("instance number is: %s" %cls.num)        >>> a1=TeamA()>>> TeamA.counter()instance number is: 1>>> a2 = TeamA()>>> TeamA.counter()instance number is: 2>>> 

靜態方法(static method): 用@staticmethod 修飾。

 

Python對象和類

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.