python 实例方法、静态方法、类方法应用场景
转自https://blog.csdn.net/sinat_38068807/article/details/86501970
# 1.实例方法/对象方法
# 实例方法或者叫对象方法,指的是我们类中定义的普通方法
# 只有实例化对象之后才可以使用的方法,该方法第一个形参接收的一定是对象本身。
class People(object):
def hello(self): # 对象本身
# print(self) # <__main__.People object at 0x0000017110F32AC8>
print('hello')
peo = People()
peo.hello()
People().hello()
# 2.静态方法
# (1).格式:在方法上面添加 @staticmethod
# (2).参数:静态方法可以有参数也可以无参数
# (3).应用场景:一般用于和类对象以及实例对象无关的代码。
# (4).使用方式: 类名.类方法名(或者对象名.类方法名)。
class Game(object):
@staticmethod
def menu(self):
# print(self) # 贪吃蛇
print('开始请按1')
print('暂停请按2')
print('退出请按3')
game = Game()
# 对象名.类方法名
game.menu('贪吃蛇')
# 类名.类方法名
Game.menu('贪吃蛇')
# 类方法
# 无需实例化,可以通过类直接调用的方法,但是方法的第一个参数接收的一定是类本身
# (1).在方法上面添加@classmethod
# (2).方法的参数为 cls 也可以是其他名称,但是一般默认为cls
# (3).cls 指向 类对象(也就是Goods)
# (4).应用场景:当一个方法中只涉及到静态属性的时候可以使用类方法(类方法用来修改类属性)。
# (5).使用 可以是 对象名.类方法名。或者是 类名.类方法名
class People(object):
role = '人类'
@classmethod
def test(cls):
print(cls) # <class '__main__.People'>
print(cls.role)
print('test')
# 使用
# 类名.类方法名
People.test()
per = People()
# 对象名.类方法名
per.test()
# 练习:使用类方法对商品打折扣
# 对象方法
class Goods:
def __init__(self, name, price):
self.name = name
self.__price = price
self.__discount = 1 # 折扣
@property
def price(self):
return self.__price*self.__discount
# 改变折扣价
def change_discount(self, new_discount):
self.__discount = new_discount
# 苹果八折
apple = Goods('苹果', 10)
apple.change_discount(0.8)
print(apple.price)
# 香蕉7折
banana = Goods('香蕉', 10)
banana.change_discount(0.7)
print(banana.price)
# 类方法
class Goods:
def __init__(self, name, price):
self.name = name
self.__price = price
@property
def price(self):
return self.__price*self.__discount
# 改变折扣价
@classmethod
def change_discount(cls, new_discount):
cls.__discount = new_discount
# 只调用一次,全部打折
Goods.change_discount(0.8)
apple = Goods('苹果', 10)
print(apple.price)