內置屬性
創建類時系統自動創建的屬性
class Person ( object ) : '''Person類1''' __slots__
= ( 'name' , 'age' ) def __init__ ( self
, name
, age
) : self
. name
= nameself
. age
= age
def eat ( self
) : print ( "eat!!!" ) p
= Person
( 'name' , 17 )
print ( dir ( p
) )
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
= age
def eat ( self
) : print ( "eat!!!" ) p
= Person
( 'name' , 19 )
print ( p
. type )
print ( Person
. type )
Person
. type = 'upq'
print ( Person
. type )
print ( p
. type )
私有屬性
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
. __name
def set_in_name ( self
, name
) : self
. __name
= name
t
= Teacher
( )
print ( "name is" , t
. _Teacher__name
)
t
. _Teacher__name
= "AA"
print ( "name is" , t
. _Teacher__name
)
t
. set_in_name
( 'pppp' )
print ( t
. get_in_name
( ) )
私有方法
class Person ( object ) : def __init__ ( self
) : self
. __p
= 100 def __xx ( self
) : print ( self
. __p
)
p1
= Person
( )
print ( p1
. _Person__p
)
p1
. _Person__xx
( )
實例方法
類方法
靜態方法
總結:實例方法 & 類方法 & 靜態方法
靜態方法:當用不到當前類和對象屬性時(感覺與當前類沒關系一樣),可以定義為靜態方法(一個定義在類中的普通方法)
class Person ( ) : type = 'type' __slots__
= ( 'name' , 'age' ) def __init__ ( self
, name
, age
) : self
. name
= nameself
. age
= age
def common ( self
) : print ( 'common' ) @classmethod def classmethod ( cls
) : cls
. type = 'class type' print ( cls
. type ) print ( 'classmethod' ) @staticmethod def staticmethod ( ) : print ( 'static' )
p
= Person
( 'name' , 77 )
p
. common
( )
p
. classmethod ( )
p
. staticmethod ( )
Person
. common
( p
)
Person
. classmethod ( )
Person
. staticmethod ( )
創作挑戰賽 新人創作獎勵來咯,堅持創作打卡瓜分現金大獎
總結
以上是生活随笔 為你收集整理的Python学习10 内置属性 对象属性 类属性 私有属性 私有方法 对象方法 类方法 静态方法 的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔 網站內容還不錯,歡迎將生活随笔 推薦給好友。