Python-类属性,实例属性,类方法,静态方法,实例方法
类属性和实例属性
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
#coding:utf-8
class Student( object ):
name = 'I am a class variable' #类变量
>>> s = Student() # 创建实例s
>>> print (s.name) # 打印name属性,因为实例并没有name属性,所以会继续查找class的name属性
Student
>>> print (Student.name) # 打印类的name属性
Student
>>> s.name = 'Michael' # 给实例绑定name属性
>>> print (s.name) # 由于实例属性优先级比类属性高,因此,它会屏蔽掉类的name属性
Michael
>>> print (Student.name) # 但是类属性并未消失,用Student.name仍然可以访问
Student
>>> del s.name # 如果删除实例的name属性
>>> print (s.name) # 再次调用s.name,由于实例的name属性没有找到,类的name属性就显示出来了
Student
|
类方法,实例方法,静态方法
实例方法,第一个参数必须要默认传实例对象,一般习惯用self。
静态方法,参数没有要求。
类方法,第一个参数必须要默认传类,一般习惯用cls。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
# coding:utf-8
class Foo( object ):
"""类三种方法语法形式"""
def instance_method( self ):
print ( "是类{}的实例方法,只能被实例对象调用" . format (Foo))
@staticmethod
def static_method():
print ( "是静态方法" )
@classmethod
def class_method( cls ):
print ( "是类方法" )
foo = Foo()
foo.instance_method()
foo.static_method()
foo.class_method()
print ( '----------------' )
Foo.static_method()
Foo.class_method()
|
运行结果:
1
2
3
4
5
6
|
是类< class '__main__.Foo' >的实例方法,只能被实例对象调用
是静态方法
是类方法
- - - - - - - - - - - - - - - -
是静态方法
是类方法
|
类方法
由于python类中只能有一个初始化方法,不能按照不同的情况初始化类,类方法主要用于类用在定义多个构造函数的情况。
特别说明,静态方法也可以实现上面功能,当静态方法每次都要写上类的名字,不方便。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
# 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)
|