python类方法的使用注意

Python (189) 2023-05-17 00:06:26

使用注意

1、@classmethod必须位于方法上面一行。

2、第一个cls必须有。

cls指的就是类对象本身。

3、类方法中访问实例属性和实例方法会导致错误。

4、子类继承父类方法时,传入cls是子类对象,而非父类对象。

5、实例对象也能对类方法进行访问。

实例

classHouse(object):

price='high'


print(House.price)
h=House()
print(h.price)

House.price='toohigh'
print(House.price)
print(h.price)

print('-'*20)
h.price='high'
print(House.price)
print(h.price)

以上就是python类方法的使用注意,希望对大家有所帮助。

本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

THE END

发表回复