对象方法&静态方法&类方法

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

class People():
      def hello(self):#self表示对象本身
            print('hello word')

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

class Game:
     #静态方法
     @staticmethod
     def show_menu():
           print('开始按钮【1】')
           print('暂停按钮【2】')
           print('停止按钮【3】')
#类名.静态方法名称()  
Game.show_menu()
#对象名.静态方法名称() 不推荐使用,麻烦
game=Game()
game.show_menu()

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

Person.test()
print('--------')
per=Person()
per.test()

练习1:使用类方法对商品进行打折扣

class Goods:
     __discount=1#折扣 默认是1
     def __init__(self,name,price):
           self.name=name
           self.__price=price
      #实际价格
     @property
     def price(self)
          return self.__price*self.__diccount
     #打折扣------>普通方法
     #def chang_discount(self,new_discount):
          self.__discount=new_discount
     @classmethod
     def chang_discount(cls,new_discount):
         cls.__discount=new_discount
     def test(self):
          pirnt('xxx')   

#给苹果的香蕉打八折
#创建苹果
apple=Goods('苹果',10)
print(apple.price)
#打八折
apple.chang_discount(0.8)
print(apple.price)
#创建香蕉
banana=Goods('香蕉',8)
print(banana.price)
banana.chang_diccount(0.8)
print(banana.price)      
#使用普通方法,每一次都是需要打折
2、使用类方法
Goods.chang_discont(0.8)#只需调动一个即可
apple=Goods('苹果',10)
print(apple.price)
banana=Goods('香蕉',8)
print(banana.price)```

猜你喜欢

转载自blog.csdn.net/qq_44240254/article/details/86498010