Python中如何区分实例方法、类方法和静态方法?

2026-05-26 15:470阅读0评论SEO基础
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计803个文字,预计阅读时间需要4分钟。

Python中如何区分实例方法、类方法和静态方法?

一、实例方法(对象方法)+ 类中的方法默认都是实例方法。

pythonclass Person(object): type='human'

def __init__(self, name, age): self.name=name self.age=age

def eat(self, food): print(f{self.name} is eating {food}.)


一、实例方法(对象方法)

  • 类中的方法默认都是实例方法。
class Person(object):
type = 'human'

def __init__(self, name, age):
self.name = name
self.age = age

def eat(self, food): # 实例方法有一个参数self,指的是实例对象
print(self.name + '正在吃' + food)


p1 = Person('张三', 18)
p1.eat('红烧牛肉泡面') # 直接使用实例对象调用方法
Person.eat(p1, '西红柿鸡蛋盖饭')
  • 使用​​对象名.方法名(参数)​​调用的方式,不需要传递self。
  • 使用​​类名.方法名(self, 参数)​​的方式,不会自动给self传参,需要手动的指定self。
阅读全文

本文共计803个文字,预计阅读时间需要4分钟。

Python中如何区分实例方法、类方法和静态方法?

一、实例方法(对象方法)+ 类中的方法默认都是实例方法。

pythonclass Person(object): type='human'

def __init__(self, name, age): self.name=name self.age=age

def eat(self, food): print(f{self.name} is eating {food}.)


一、实例方法(对象方法)

  • 类中的方法默认都是实例方法。
class Person(object):
type = 'human'

def __init__(self, name, age):
self.name = name
self.age = age

def eat(self, food): # 实例方法有一个参数self,指的是实例对象
print(self.name + '正在吃' + food)


p1 = Person('张三', 18)
p1.eat('红烧牛肉泡面') # 直接使用实例对象调用方法
Person.eat(p1, '西红柿鸡蛋盖饭')
  • 使用​​对象名.方法名(参数)​​调用的方式,不需要传递self。
  • 使用​​类名.方法名(self, 参数)​​的方式,不会自动给self传参,需要手动的指定self。
阅读全文