python 給對象綁定屬性和方法

來源:互聯網
上載者:User

標籤:綁定   出現   山東   zha   imp   add   init   調用   ini   

# 以c語言為主是靜態語言,運行之前先編譯,在啟動並執行過程中不允許編輯代碼
# 在啟動並執行過程中,可以改變,可以添加屬性,就是屬於動態語言(python)


# python動態添加屬性以及方法
class Test(object):
pass

# t = Test()
# print(dir(t))


# 啟動並執行過程中給對象綁定(添加)屬性
class Person(object):
  def __init__(self,newName,newAge):
    self.name = newName
    self.age = newAge
  def eat(self):
  print("---%s正在吃--"%self.name)
# 添加屬性
# laowang = Person("老王",100000)
# print(laowang.name)
# print(laowang.age)
# laowang.addr = ‘山東‘ #給對象添加屬性,屬性和對象綁定到了一起
# print(laowang.addr)

# laozhao = Person("老趙",18)
# print(laozhao.name)
# print(laozhao.age)
# # print(laozhao.addr)

# Person.num = 100 #給類添加屬性,屬性和類綁定到了一起
# print(laowang.num)
# print(laozhao.num)

# 添加方法

def run(self):
  print("---%s正在吃--"%self.name)


p1 = Person("p1",10)
p1.eat()

# p1.run = run  #這個方法式錯誤的
# p1.run() #雖然p1對象中的run屬性已經指向了10行的函數,但這句代碼還是不正確,因為run屬性指向的函數時候來添加的,p1.run()的時候,並沒有把p1當作第一個參數,導致了第10行的函數調用的時候,出現了缺少參數的問題

 

# import types
# types.MethodType() #把函數綁定到執行個體對象上

import types
p1.run = types.MethodType(run,p1)
p1.run()

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.