日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python的实例属性和静态属性_Python面向对象之静态属性、类方法与静态方法分析...

發布時間:2025/3/15 python 36 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python的实例属性和静态属性_Python面向对象之静态属性、类方法与静态方法分析... 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

本文實例講述了Python面向對象之靜態屬性、類方法與靜態方法。分享給大家供大家參考,具體如下:

1. 靜態屬性:在函數前加@property,將函數邏輯”封裝“成數據屬性,外部直接調用函數名,如同調用屬性一樣。這個函數是可以調用對象和類的屬性的。

# -*- 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.width

r1 = Room('臥室','alex',100,1000)

print(r1.cal_area)

#r1.cal_area = 10 并不是真實的數據屬性,所以不可以在外部直接賦值。

運行結果:

100000

2. 類方法:在類的方法前添加@classmethod,不需要實例化,直接調用類的該方法。可以訪問類的數據屬性,但是不可以訪問對象的數據屬性。

# -*- 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):

#這么寫會報錯,因為name是對象的數據屬性,而類方法是不可以訪問實例的屬性的

#print('%s的房間風格是%s'%(cls.name,cls.style))

print('房間的風格是%s'%(cls.style))

#類方法的定義只是為了類去調用

Room.tell_style()

運行結果:

房間的風格是別墅

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

# -*- 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):

#這么寫會報錯,因為name是對象的數據屬性,而類方法是不可以訪問實例的屬性的

#print('%s的房間風格是%s'%(cls.name,cls.style))

print('房間的風格是%s'%(cls.style))

@staticmethod

def shower():

print("洗澡")

def test(self):

print("這不是靜態方法,而且自動生成參數,必須要有實例")

Room.shower()

r1 = Room('別墅','alex',10,10)

r1.shower() #這么調用也沒有問題

#報錯,因為不是靜態方法,必須要實例化

Room.test()

運行結果:

洗澡

洗澡

Traceback (most recent call last):

File "C:\py\jb51PyDemo\src\Demo\test.py", line 26, in

Room.test()

TypeError: unbound method test() must be called with Room instance as first argument (got nothing instead)

希望本文所述對大家Python程序設計有所幫助。

總結

以上是生活随笔為你收集整理的python的实例属性和静态属性_Python面向对象之静态属性、类方法与静态方法分析...的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。