亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

python中類的屬性和方法介紹

 更新時(shí)間:2018年11月27日 08:35:32   投稿:laozhang  
在本篇內(nèi)容里小編給大家整理了關(guān)于python中類的屬性知識(shí)點(diǎn)以及使用方法介紹,需要的朋友們參考下。

Python-類屬性,實(shí)例屬性,類方法,靜態(tài)方法,實(shí)例方法

類屬性和實(shí)例屬性

#coding:utf-8
class Student(object):
  name = 'I am a class variable' #類變量
>>> s = Student() # 創(chuàng)建實(shí)例s
>>> print(s.name) # 打印name屬性,因?yàn)閷?shí)例并沒有name屬性,所以會(huì)繼續(xù)查找class的name屬性
Student
>>> print(Student.name) # 打印類的name屬性
Student
>>> s.name = 'Michael' # 給實(shí)例綁定name屬性
>>> print(s.name) # 由于實(shí)例屬性優(yōu)先級(jí)比類屬性高,因此,它會(huì)屏蔽掉類的name屬性
Michael
>>> print(Student.name) # 但是類屬性并未消失,用Student.name仍然可以訪問
Student
>>> del s.name # 如果刪除實(shí)例的name屬性
>>> print(s.name) # 再次調(diào)用s.name,由于實(shí)例的name屬性沒有找到,類的name屬性就顯示出來了
Student

類方法,實(shí)例方法,靜態(tài)方法

實(shí)例方法,第一個(gè)參數(shù)必須要默認(rèn)傳實(shí)例對象,一般習(xí)慣用self。

靜態(tài)方法,參數(shù)沒有要求。

類方法,第一個(gè)參數(shù)必須要默認(rèn)傳類,一般習(xí)慣用cls。

# coding:utf-8
class Foo(object):
  """類三種方法語法形式"""
 
  def instance_method(self):
    print("是類{}的實(shí)例方法,只能被實(shí)例對象調(diào)用".format(Foo))
 
  @staticmethod
  def static_method():
    print("是靜態(tài)方法")
 
  @classmethod
  def class_method(cls):
    print("是類方法")
 
foo = Foo()
foo.instance_method()
foo.static_method()
foo.class_method()
print('----------------')
Foo.static_method()
Foo.class_method()

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

是類<class '__main__.Foo'>的實(shí)例方法,只能被實(shí)例對象調(diào)用
是靜態(tài)方法
是類方法
----------------
是靜態(tài)方法
是類方法

類方法

由于python類中只能有一個(gè)初始化方法,不能按照不同的情況初始化類,類方法主要用于類用在定義多個(gè)構(gòu)造函數(shù)的情況。
特別說明,靜態(tài)方法也可以實(shí)現(xiàn)上面功能,當(dāng)靜態(tài)方法每次都要寫上類的名字,不方便。

# coding:utf-8
class Book(object):
 
  def __init__(self, title):
    self.title = title
 
  @classmethod
  def class_method_create(cls, title):
    book = cls(title=title)
    return book
 
  @staticmethod
  def static_method_create(title):
    book= Book(title)
    return book
 
book1 = Book("use instance_method_create book instance")
book2 = Book.class_method_create("use class_method_create book instance")
book3 = Book.static_method_create("use static_method_create book instance")
print(book1.title)
print(book2.title)
print(book3.title)

相關(guān)文章

最新評論