Python物件導向

來源:互聯網
上載者:User

標籤:類的方法   def   print   des   ==   類的建構函式   recent   函數   編程   

Python物件導向編程


類與對象的區別
類是客觀世界中的事物的抽象,比如人類、球類
對象是類執行個體化的實體,比如足球,籃球
執行個體說明:
球類可以對球的特徵和行為進行抽象,然後可以執行個體化一個真實的球實體出來(執行個體化就是創造對象)

 

類的建立格式:

class ClassName:
   類的內容


class Fruit:
    def __init__(self):  ###__init__為類的建構函式
        self.name = name   ### 類的屬性
        self.color = color
    def grow(self): ###定義grow函數,在類中函數稱為方法
         print "Fruit grow"

**類的方法必須有一個self參數,在方法調用時,可以不傳遞這個參數

 

方法:類中定義的函數

屬性:類中的定義的變數

 

類的執行個體化

根據類來建立的對象的稱為執行個體化

 

class Dog():
    def __init__(self,name,age):     
         self.name = name
         self.age = age

    def sit(self):    ##類的方法
          print(self.name.title() + " is now sitting.")
    def roll_over(self):    
          print(self.name.title() + " rollwd over!")

my_dog = Dog(‘willie‘,‘6‘)    ###類的執行個體化

print("My dog‘s name is " + my_dog.name.title() + ‘.‘)
print("My dog is " + str(my_dog.age) + " years old." )

結果:

My dog‘s name is Willie.
My dog is 6 years old.

 

調用方法
將類執行個體化後,可以通過句號標記法來調用類中定義的方法

my_dog.sit()
my_dog.roll_over()


結果:
Willie is now sitting.
Willie rolled over!

 

 

類的屬性

類的屬性按使用範圍可以分為共有屬性和私人屬性,類的屬性範圍取決於屬性的名稱
公有屬性: 在類中和類外都能調用的屬性
私人屬性: 不能再類外及類以外的函數調用的屬性
定義方式:以"__"雙底線開始的成員變數就是私人屬性

 

執行個體:

#!/usr/bin/python
class People(object):
      color = ‘yellow‘
      __age = 30 ####私人屬性
def think(self):
     self.color = ‘black‘
     print "i am a %s" % self.color
     print "I am a thinker"
     print self.__age ###調用類的私人屬性
ren = People()
print ren.color
ren.think()
~
執行指令碼
[[email protected] day04]# python class1.py
yellow
i am a black
I am a thinker
30

=====================================================
如果在類外中調用私人屬性,會提示找不到屬性
#!/usr/bin/python

class People(object):
      color = ‘yellow‘
     __age = 30
     def think(self):
          self.color = ‘black‘
          print "i am a %s" % self.color
          print "I am a thinker"
          print self.__age
ren = People()
print ren.color
ren.think()
print ren.__age ####調用類的私人屬性
~
執行
提示找不到屬性
Traceback (most recent call last):
File "class1.py", line 14, in <module>
print ren.__age
AttributeError: ‘People‘ object has no attribute ‘__age‘

 

 

 

類的方法

方法的定義和函數一樣,但是需要self作為第一個參數
類型:
公有方法:在類中和類外都能調用的方法
私人方法: 不能被類的外部調用,在方法前面加上"__"雙底線就是私人方法
self參數
用於區分函數和類的方法(必須有一個self) self參數表示執行對象本身
===============================================================
公有方法執行個體:
#!/usr/bin/python
#coding:utf8
class People(object):
   color = ‘yellow‘
   __age = 30
def think(self):
    self.color = ‘black‘
    print "i am a %s" % self.color
    print "I am a thinker"
    print self.__age
def test(self):
    self.think()    ####調用方法think
jack = People()
jack.test()

執行
[[email protected] day04]# python class2.py
i am a black
I am a thinker
30

===================================================================
私人方法執行個體:

#!/usr/bin/python
#coding:utf8
class People(object):
     color = ‘yellow‘
    __age = 30
def think(self):
    self.color = ‘black‘
    print "i am a %s" % self.color
    print "I am a thinker"
    print self.__age
def __talk(self):
    print "i am talking with tom"
def test(self):
    self.__talk()    ###調用私人方法talk
jack = People()
jack.test()

執行

[[email protected] day04]# python class2.py
i am talking with tom

 

類的繼承

一個類繼承另外一個類時,會獲得另外一個類的所有屬性和方法,原有的類成為父類,而新類稱為子類,子類基礎父類的所有屬性和方法

class Car():

      def __init__(self, make, model, year):
           self.make = make
           self.model = model
           self.year = year
           self.odometer_reading = 0

def get_descirptive_name(self):
       long_name = str(self.year) + ‘ ‘ + self.make + ‘ ‘ + self.model
       return long_name.title()

def read_odometer(self):
       print("This car has " + str(self.odometer_reading) + " miles on it.")

class ElectircCar(Car): ###定義子類ElectricCar
        def __init__(self,make,model,year):
              super().__init__(make,model,year)      ###初始化父類的屬性,調用electircar的父類方法__init__(),使electircCar包含父類的所有屬性

my_tesla = ElectircCar(‘tesla‘,‘model S‘,2016)     ##建立ElectircCar類執行個體,調用父類Car定義的方法__init__()
print(my_tesla.get_descirptive_name())     #調用父類方法


執行結果
2016 Tesla Model S

###建立子類時,父類必須包含在當前檔案中,且位於子類前面,必須在括弧內指定父類的名稱
super()為了將父類的和子類關聯起來

 


子類定義屬性和方法

class Car():

      def __init__(self, make, model, year):
      self.make = make
      self.model = model
      self.year = year
      self.odometer_reading = 0

def get_descirptive_name(self):
      long_name = str(self.year) + ‘ ‘ + self.make + ‘ ‘ + self.model
      return long_name.title()

def read_odometer(self):
      print("This car has " + str(self.odometer_reading) + " miles on it.")

class ElectircCar(Car):
     def __init__(self,make,model,year):
          super().__init__(make,model,year)
self.battery_size = 70     ##子類屬性
def describe_battery(self):    ##子類方法
       print("This car has a " + str(self.battery_size) + "-kwh battery.")

my_tesla = ElectircCar(‘tesla‘,‘model S‘,2016)
print(my_tesla.get_descirptive_name())
my_tesla.describe_battery()


執行結果

2016 Tesla Model S
This car has a 70-kwh battery.

 

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.