国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python面向?qū)ο笾o態(tài)屬性、類方法與靜態(tài)方法分析

2020-01-04 14:39:39
字體:
供稿:網(wǎng)友

本文實(shí)例講述了Python面向?qū)ο笾o態(tài)屬性、類方法與靜態(tài)方法。分享給大家供大家參考,具體如下:

1. 靜態(tài)屬性:在函數(shù)前加@property,將函數(shù)邏輯”封裝“成數(shù)據(jù)屬性,外部直接調(diào)用函數(shù)名,如同調(diào)用屬性一樣。這個(gè)函數(shù)是可以調(diào)用對(duì)象和類的屬性的。

# -*- coding:utf-8 -*-class Room:  def __init__(self,name,owner,width,length):    self.name = name    self.owner = owner    self.width = width    self.length = length  @property  def cal_area(self):    return self.length * self.widthr1 = Room('臥室','alex',100,1000)print(r1.cal_area)#r1.cal_area = 10  并不是真實(shí)的數(shù)據(jù)屬性,所以不可以在外部直接賦值。

運(yùn)行結(jié)果:

100000

2. 類方法:在類的方法前添加@classmethod,不需要實(shí)例化,直接調(diào)用類的該方法。可以訪問類的數(shù)據(jù)屬性,但是不可以訪問對(duì)象的數(shù)據(jù)屬性。

# -*- coding:utf-8 -*-class Room:  style = '別墅'  def __init__(self,name,owner,width,length):    self.name = name    self.owner = owner    self.width = width    self.length = length  @property  def cal_area(self):    return self.length * self.width  @classmethod  def tell_style(cls):    #這么寫會(huì)報(bào)錯(cuò),因?yàn)閚ame是對(duì)象的數(shù)據(jù)屬性,而類方法是不可以訪問實(shí)例的屬性的    #print('%s的房間風(fēng)格是%s'%(cls.name,cls.style))    print('房間的風(fēng)格是%s'%(cls.style))#類方法的定義只是為了類去調(diào)用Room.tell_style()

運(yùn)行結(jié)果:

房間的風(fēng)格是別墅

3. 靜態(tài)方法:在類的方法前加@staticmethod,該方法只是名義上的歸屬類管理,實(shí)例和類的屬性均不可以訪問,僅僅是類的工具包。

# -*- coding:utf-8 -*-class Room:  style = '別墅'  def __init__(self,name,owner,width,length):    self.name = name    self.owner = owner    self.width = width    self.length = length  @property  def cal_area(self):    return self.length * self.width  @classmethod  def tell_style(cls):    #這么寫會(huì)報(bào)錯(cuò),因?yàn)閚ame是對(duì)象的數(shù)據(jù)屬性,而類方法是不可以訪問實(shí)例的屬性的    #print('%s的房間風(fēng)格是%s'%(cls.name,cls.style))    print('房間的風(fēng)格是%s'%(cls.style))  @staticmethod  def shower():    print("洗澡")  def test(self):    print("這不是靜態(tài)方法,而且自動(dòng)生成參數(shù),必須要有實(shí)例")Room.shower()r1 = Room('別墅','alex',10,10)r1.shower()  #這么調(diào)用也沒有問題#報(bào)錯(cuò),因?yàn)椴皇庆o態(tài)方法,必須要實(shí)例化Room.test()

運(yùn)行結(jié)果:

洗澡
洗澡
Traceback (most recent call last):
  File "C:/py/jb51PyDemo/src/Demo/test.py", line 26, in <module>
    Room.test()
TypeError: unbound method test() must be called with Room instance as first argument (got nothing instead)

希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。


注:相關(guān)教程知識(shí)閱讀請(qǐng)移步到python教程頻道。
發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 龙井市| 兖州市| 同德县| 敦化市| 阳曲县| 任丘市| 通山县| 张家口市| 东安县| 孝义市| 翁源县| 花莲县| 七台河市| 荃湾区| 南涧| 白水县| 防城港市| 南安市| 镇平县| 石台县| 哈尔滨市| 盈江县| 广丰县| 云南省| 林口县| 临桂县| 利川市| 扎囊县| 龙游县| 稻城县| 桃园市| 阳高县| 大安市| 绿春县| 天全县| 东方市| 博客| 南昌县| 盐津县| 襄汾县| 高邮市|