Python中实例方法,静态方法,类方法的区别
实例方法
- 实例方法:会使用实例对象的属性,self 指向调用这个方法的实例对象
- 两种调用方法:
- 1,实例对象.方法名===》不需要手动给self 传参,会自动将实例对象传递给self
- 2, 类对象.方法名 ===》需要给self 传参
静态方法:
如果一个方法,既不用实例对象,也用不到类对象感觉就像和这个类没有关系一样,可以把这个方法定义为静态方法
类方法:
会有一个cls 参数,指类对象,如果一个方法只使用到类属性,可以将这个方法定义为类方法
# @作者:Sophia xu
# @时间:7/28/2021
class Person(object):
type='human'
def __init__(self,name,age):
self.name=name
self.age=age
def eat(self,food): #实例方法
print(self.type) #实例方法也可以访问类属性
print(self.name+'吃'+food)
@staticmethod
def demo():
print('hello')
@classmethod
def test(cls): #类方法访问类属性
print(cls.type)
p1= Person('张三',10)
p1.eat('红烧肉')
Person.eat(p1,'肉肉')
Person.demo()
p1.demo()
p1.test()
Person.test()