实例方法/对象方法 实例方法或者叫对象方法,指的是我们在类中定义的普通方法
只有实例化后才能使用的方法,该方法的第一个形参接收的一定是对象的本身
静态方法
- 格式:在方法上面添加 @staticmethod
- 参数:静态方法可以有参数也可以无参数
- 应用场景:一般用于类对象以及实例对象无关的代码
- 使用方式:类名.静态方法名(或者对象名.静态方法名)
class Dog:
@property
def eat(self):
print("吃骨头")
# Dog.eat() # 普通方法只能通过对象调用的方式使用
dog =Dog()
dog.eat
# 吃骨头
class Game:
@staticmethod
def show_menu(x):
print(x)
print("开始按钮1")
print("暂停按钮2")
print("结束按钮3")
# g = Game()
# g.show_menu()
Game.show_menu(2)
# 2
# 开始按钮1
# 暂停按钮2
# 结束按钮3
类方法
class Person:
role = '人类'
@classmethod
def test(cls): #第一个参数必须是当前类对象,通过cls传递类的属性和方法(不能传实例的属性和方法)
print(cls.role)
print("----in test----")
# Person.test()
p1 =Person()
p1.test()
# 人类
# ----in test----