类方法/静态方法/实例方法

classPerson:

@classmethod

def eat(self):   

print("吃饭")

@staticmethod

def speak():

print("说话")

def run(self):

print("走路")

A Person.speak();

B Person.eat();

C Person.run();

D Person.run(Person())

让我们分析每个选项:

A: Person.speak(); -- 静态方法可以通过类直接调用,不需要参数。所以这个应该正常调用。

B: Person.eat(); -- 类方法也可以通过类直接调用。类方法的第一个参数是cls,但这里定义时用了self(实际上在类方法中,通常用cls,但名称不重要)。所以 Person.eat() 会正常调用,将类作为第一个参数传递。

C: Person.run(); -- 这是一个实例方法,需要通过实例调用。如果通过类直接调用,缺少self参数,所以会报错(TypeError: run() missing 1 required positional argument: 'self')。

D: Person.run(Person()); -- 这实际上是使用类调用实例方法,但显式传递了一个实例作为self参数。Person()创建一个实例,然后作为参数传递给run方法。这应该可以工作,尽管通常我们写成 instance.run()。

全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务