python中类的属性和方法介绍
Python-类属性,实例属性,类方法,静态方法,实例方法
类属性和实例属性
#coding:utf-8 classStudent(object): name='Iamaclassvariable'#类变量 >>>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 >>>dels.name#如果删除实例的name属性 >>>print(s.name)#再次调用s.name,由于实例的name属性没有找到,类的name属性就显示出来了 Student
类方法,实例方法,静态方法
实例方法,第一个参数必须要默认传实例对象,一般习惯用self。
静态方法,参数没有要求。
类方法,第一个参数必须要默认传类,一般习惯用cls。
#coding:utf-8
classFoo(object):
"""类三种方法语法形式"""
definstance_method(self):
print("是类{}的实例方法,只能被实例对象调用".format(Foo))
@staticmethod
defstatic_method():
print("是静态方法")
@classmethod
defclass_method(cls):
print("是类方法")
foo=Foo()
foo.instance_method()
foo.static_method()
foo.class_method()
print('----------------')
Foo.static_method()
Foo.class_method()
运行结果:
是类的实例方法,只能被实例对象调用 是静态方法 是类方法 ---------------- 是静态方法 是类方法
类方法
由于python类中只能有一个初始化方法,不能按照不同的情况初始化类,类方法主要用于类用在定义多个构造函数的情况。
特别说明,静态方法也可以实现上面功能,当静态方法每次都要写上类的名字,不方便。
#coding:utf-8
classBook(object):
def__init__(self,title):
self.title=title
@classmethod
defclass_method_create(cls,title):
book=cls(title=title)
returnbook
@staticmethod
defstatic_method_create(title):
book=Book(title)
returnbook
book1=Book("useinstance_method_createbookinstance")
book2=Book.class_method_create("useclass_method_createbookinstance")
book3=Book.static_method_create("usestatic_method_createbookinstance")
print(book1.title)
print(book2.title)
print(book3.title)