python 基础 实例方法 、类方法 和静态方法

1 实例方法/对象方法

实例方法或者叫对象方法,指的是我们在类中定义的普通方法。

只有实例化对象之后才可以使用的方法,该方法的第一个形参接受的一定是对象本身!

class Person():
    def hello(self):   #self指的就是对象本身
        print('hello world')
        

2  静态方法

(1) 格式 : 在方法上面添加 @staticmethod

(2)参数 :  静态方法可以有参数也可以无参数

(3)应用场景:一般用于和类对象以及实例对象无关的代码

(4)使用方式:类名.类方法名(或者对象名.类方法名)

class Game():

    def __init__(self,name,age):
        self.name = name
        self.age = age
    
    #例如此方法是射击方法
    #def test1(self):
    #    self.name
    #    self.age

    @staticmethod
    def mune():
        print('开始按钮【1】')
        print('暂停按钮【2】')
        print('结束按钮【3】')
Game.mune()  #使用类名调用
#使用对象调用
game = Game('穿越火线',10)
game.mune()
"""
开始按钮[1]
暂停按钮[2]
结束按钮[3]

开始按钮[1]
暂停按钮[2]
结束按钮[3]
"""

3 类方法

无需实例化,可以通过直接调用的方法,但是方法的第一个参数接受的一定是类本身

(1)在方法上面添加@classmethod

(2)方法的参数为cls 也可以是其他名称,但是一般默认为cls

(3)cls 指向类对象 (也就是Goods)

(4)应用场景:当一个方法中只涉及到静态属性的时候可以使用类方法(类方法用来修改属性)

(5)使用可以是  对象名.类方法名。或者是 类名.类方法名

class Dog:
    role = '狗'

    def test(self):
        #做一些逻辑判断
        pass

    @classmethod
    def test2(cls):
        """cls 是参数 是指向类对象本身"""
        print(cls.role)
        print(Dog.role)   #直接使用类名也可以

#Dog  类名  也是对象名
print(Dog.role)
#调用方法
Dog.test2()
#也可以使用对象调用
dog = Dog()
dog.test2()

练习 :每种商品都可以打折

"""使用之前的方法"""  每个货物都要重新打折  
class Goods:
    
    def __init__(self,name,price): 
        self.name = name
        self.__price = price
        self.__discount = discount  #不折扣或者之前的折扣
    
    @property    
    def price(self):
        return self.__price * __discount = self.__price

    def change_discount(self,new_discount)   #新的折扣
        __discount = new_discount

apple = Goods('苹果',10)  #货物是苹果  价格是10
apple.change_discount(0.8) #新的折扣
print(apple,price)

banana = Goods('香蕉',20)
banana.change_discount(0.7)
print(banana,price)
"""使用classmetho方法"""
class Goods:
    __discount = discount  #所有的商品遵循此一个折扣

    def __init__(self,name,price): 
        self.name = name
        self.__price = price
            
    @property    
    def price(self):
        return self.__price * __discount = self.__price
    
    @classmethod
    def change_discount(self,new_discount)   #新的折扣
        __discount = new_discount


Good.change__discount(0.8)
apple = Goods('苹果',10)  #货物是苹果  价格是10
print(apple,price)

banana = Goods('香蕉',20)
print(banana,20)

 

你可能感兴趣的:(python,新人学习Python必关注,零基础)