目录
这块要分清几个概念
self | 对象名 |
cls | 类名 |
静态属性 | 类属性 |
一,实例方法
self就是要调用这个方法的对象
只有实例化对象之后才可以使用的方法,该方法的第一个形参接收的一定是对象本身!(self)
方 法类型 | 格式 | 参数 | 应用场景 | 使用方法 |
静态方法 | 在方法的上面添加 @staticmethod | 可以有参数 也可以没有参数 | 一般用于和类对象,实例对象无关的代码 | 1.类名.类方法名 2.对象名.类方法名 |
类方法 | 在方法的上面添加 @classmethod | 参数为cls,也可以为其他参数,但是默认为cls | 当一个方法中只有类属性(静态属性)的时候,可以使用类方法 类方法用来修改类属性 | 1.类名.类方法名 2.对象名.类方法名 |
二,静态方法:@staticmethod
# 1.静态方法的使用场景:
class Game:
def __init__(self, name, age):
self.name = name
self.age = age
# 例如此方法是射击方法
# def test1(self):
# self.name
# self.age
@staticmethod # 静态方法
def menu():
print('开始按钮【1】')
print('暂停按钮【2】')
print('结束按钮【3】')
# 一般情况用类名去调用就行了
Game.menu() # 使用类名调用
game = Game('双截龙', 10) # 使用实例对象调用
game.menu()
三,类方法:@classmethod
cls就是类名
静态属性就是类属性
# cls是类名
# self是对象名
class Dog:
role = '狗'
def test(self):
# 做一些逻辑操作
pass
@classmethod
def test2(cls): # 类方法的参数一般默认为cls
'''cls参数是指向类对象本身
cls其实就是Dog'''
print(cls.role)
print(Dog.role) # 直接使用类名也可以
print(Dog.role)
# 调用类方法
Dog.test2()
# 使用实例对象调用方法
dog = Dog()
dog.test2()
#
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) # 8
# 香蕉打七折
banana = Goods('香蕉', 20)
banana.change_discount(0.7)
print(banana.price) # 14
# 全场打八折
class Goods:
__discount = 1 # 折扣,是类属性
def __init__(self, name, price):
self.name = name
self.__price = price
@property
def price(self):
return self.__price * self.__discount # self.__discount其实就是__discount类属性
# 改变折扣价格
@classmethod # 类方法
# 静态属性就是累属性
# 如果一个方法里面只有静态属性的话,就可以用类方法,cls就是类名Goods
def change_discount(cls, new_discount):
cls.__discount = new_discount
Goods.change_discount(0.8)
apple = Goods('苹果', 10)
banana = Goods('香蕉', 20)
print(apple.price)
print(banana.price)