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

歡迎訪問 生活随笔!

生活随笔

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

python

Python学习10 内置属性 对象属性 类属性 私有属性 私有方法 对象方法 类方法 静态方法

發布時間:2023/12/13 python 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Python学习10 内置属性 对象属性 类属性 私有属性 私有方法 对象方法 类方法 静态方法 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

內置屬性

創建類時系統自動創建的屬性


# 內置屬性:dir(對象),列出所有的內置屬性 class Person(object):'''Person類1'''# Person類2__slots__ = ('name', 'age')def __init__(self, name, age):self.name = nameself.age = agedef eat(self):print("eat!!!")p = Person('name',17) print(dir(p)) # 輸出 # ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'eat'] print(p.__class__) #將對象所支持的所有屬性和函數列出。 print(p.__dir__) #顯示的是多行注釋 print(p.__doc__) print(Person.__doc__) #主方法 print(p.__module__)

對象屬性

類屬性



# 類屬性 class Person(object):type = 'mm'__slots__ = ('name', 'age')def __init__(self, name, age):self.name = nameself.age = agedef eat(self):print("eat!!!")p=Person('name',19) #通過對象和類名調用類屬性 print(p.type) print(Person.type) #只能通過類名修改類屬性 Person.type='upq' print(Person.type) print(p.type) #輸出 # mm # mm # upq # upq

私有屬性




# 私有屬性 class Teacher():def __init__(self):self.__name='ert'self.__level=99#獲取老師的等級def get_level(self):return self.__level#獲取名字def get_in_name(self):return self.__namedef set_in_name(self,name):self.__name=name t=Teacher() # #獲取私有屬性1 print("name is",t._Teacher__name) #輸出GG t._Teacher__name="AA" #被改變了 print("name is",t._Teacher__name) #輸出AA #獲取私有屬性2 t.set_in_name('pppp') print(t.get_in_name())#輸出 # name is GG # name is AA # pppp

私有方法


#function:私有方法 class Person(object):def __init__(self):self.__p=100def __xx(self):print(self.__p) p1=Person() print(p1._Person__p) p1._Person__xx()

實例方法


類方法


靜態方法



總結:實例方法 & 類方法 & 靜態方法

靜態方法:當用不到當前類和對象屬性時(感覺與當前類沒關系一樣),可以定義為靜態方法(一個定義在類中的普通方法)

# author:dq # project:PythonProject # date:2021年10月21日 # function:實例方法 & 類方法 & 靜態方法class Person():type = 'type'__slots__ = ('name', 'age')def __init__(self, name, age):self.name = nameself.age = age# 實例方法def common(self):print('common')# 類方法@classmethoddef classmethod(cls):cls.type = 'class type'print(cls.type)print('classmethod')# 靜態方法@staticmethoddef staticmethod():print('static') p=Person('name',77) #對象調用 p.common() p.classmethod() p.staticmethod() #類調用 Person.common(p) Person.classmethod() Person.staticmethod() 創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎

總結

以上是生活随笔為你收集整理的Python学习10 内置属性 对象属性 类属性 私有属性 私有方法 对象方法 类方法 静态方法的全部內容,希望文章能夠幫你解決所遇到的問題。

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