网络编程
位置:首页>> 网络编程>> Python编程>> 深入解析python中的实例方法、类方法和静态方法

深入解析python中的实例方法、类方法和静态方法

作者:李嘉豪554  发布时间:2022-07-23 09:05:57 

标签:python,静态,方法,实例

1、实例方法/对象方法

实例方法或者叫对象方法,指的是我们在类中定义的普通方法。
只有实例化对象之后才可以使用的方法,该方法的第一个形参接收的一定是对象本身

深入解析python中的实例方法、类方法和静态方法

2、静态方法

(1).格式:在方法上面添加 @staticmethod
(2).参数:静态方法可以有参数也可以无参数
(3).应用场景:一般用于和类对象以及实例对象无关的代码。
(4).使用方式: 类名.类方法名(或者对象名.类方法名)。

定义一个静态方法


class Game:

@staticmethod
 def menu():
   print('------')
   print('开始[1]')
   print('暂停[2]')
   print('退出[3]')

Game.menu()

3、类方法

无需实例化,可以通过类直接调用的方法,但是方法的第一个参数接收的一定是类本身
(1).在方法上面添加@classmethod
(2).方法的参数为 cls 也可以是其他名称,但是一般默认为cls
(3).cls 指向 类对象
(5).应用场景:当一个方法中只涉及到静态属性的时候可以使用类方法(类方法用来修改类属性)。
(5).使用 可以是 对象名.类方法名。或者是 类名.类方法名


class Person:
 type = '人类'

@classmethod
 def test(cls):
   print(cls.type)

Person.test()

举例:使用类方法对商品进行统一打折


class Goods:
 __discount = 1

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

@classmethod
 def change_discount(cls, new_discount):
   cls.__discount = new_discount

@property
 def finally_price(self):
   return self.price * self.__discount

banana = Goods('香蕉', 10)
apple = Goods('苹果', 16)
Goods.change_discount(0.8)
print(banana.finally_price)
print(apple.finally_price)

Goods.change_discount(0.5)
print(banana.finally_price)
print(apple.finally_price)

输出为:

8.0
12.8
5.0
8.0

以上所述是小编给大家介绍的python中的实例方法、类方法和静态方法详解整合网站的支持!

来源:https://blog.csdn.net/weixin_44251004/article/details/86499231#3_28

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com