Class() 类属性,类方法,实例方法,静态方法
Python中Class()类主要包括 类属性,类方法,实例方法,静态方法四个部分。
他们之间的区别可以在下述的代码中体现。
class Student():
name = '张三'
def __init__(self,name,age):
self.name = name
self.age = age
#实例方法
def eat(self):
print(self.name+'在吃饭')
@staticmethod
#静态方法
def eat_staticmethod():
print(Student.name+'在吃饭')
@classmethod
#类方法
def eat_class_method(cls):
print(cls.name + '在吃饭')
stu = Student('liumys',20)
stu.eat()
print('-----------')
stu.eat_staticmethod()
print('---------')
stu.eat_class_method()
print('---------')
print(stu.name)
print('---------')
print(Student.name)
输出结果
liumys在吃饭
-----------
张三在吃饭
---------
张三在吃饭
---------
liumys
---------
张三
进程已结束,退出代码0
我们可以看到,实例方法中调用的self.name指向的是实例属性‘liucmys’,但是类方法和静态方法调用的name指向的是‘张三’,说明这两个方法指向的是类属性本身的name。
由此我们也可以知道,实例对象stu的属性name指向的是该实例中的,并不会对类属性进行改变。
类对象中动态属性与动态方法绑定
动态绑定即为在对某一个具体实例进行绑定属性与方法的情况。可以从下面代码中了解到动态绑定的性质。
class Student():
name = '张三'
def __init__(self,name,age):
self.name = name
self.age = age
def eat(name):
print(name+'在吃饭')
stu1 = Student('liucmys',24)
stu1.eat = eat
stu1.eat(stu1.name)
print('--------')
stu2 = Student('张三',24)
stu2.eat(stu2.name)
输出结果
liucmys在吃饭
--------
Traceback (most recent call last):
File "C:\Users\Administrator\Desktop\DL\demo3.py", line 15, in <module>
stu2.eat(stu2.name)
AttributeError: 'Student' object has no attribute 'eat'
进程已结束,退出代码1
在代码中,我们定义了Student()类,有定义了函数eat(),在引入两个实例stu1和stu2,我们将函数eat绑定到stu1这个实例上,然后成功调用,但是实例stu2并没有eat这个方法,由此我们可以得到,动态方法的绑定仅对绑定的实例对象有作用,并不改变类的方法,也不改变其他的实例的方法。
下面是对动态属性的绑定实验。
class Student():
name = '张三'
def __init__(self,name,age):
self.name = name
self.age = age
def eat(name):
print(name+'在吃饭')
stu1 = Student('liucmys',24)
#stu1.eat = eat
#stu1.eat(stu1.name)
stu1.height = 180
print(stu1.height)
print('--------')
stu2 = Student('张三',24)
#stu2.eat(stu2.name)
print(stu2.height)
输出结果
180
--------
Traceback (most recent call last):
File "C:\Users\Administrator\Desktop\DL\demo3.py", line 18, in <module>
print(stu2.height)
AttributeError: 'Student' object has no attribute 'height'
进程已结束,退出代码1
通过输出结果我们可以看出,动态属性的绑定特性与动态方法的绑定特性是一致的。