目录
一、实例方法/对象方法
1.实例方法:
普通的在类中定义的方法,实例化对象之后才可以用
该方法第一个参数必须是参数本身,
二、静态方法
1.格式:
在方法上面添加@staticmethod
2,。应用场景:
一般用于和类对象及实例对象无关的代码
3.使用方式:
类名。类方法名
@staticmethod
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('双截龙',12)
game.mune()
三、类方法
1.定义:
可以直接通过类直接调用方法,但是方法的第一个参数接收的一定是类本身。
(1.)在方法上面添加@classmethod
(2).方法的参数为cls,也可以是其他名称,但一般默认为cls
(3).cls指向类对象(也就是类名,类名也叫类对象)
(4).应用场景:当一个方法中只涉及到静态属性(类属性)的时候可以使用类方法,(使用类方法类修改类属性)
(5).调用格式:对象名.类方法名 // 类名.类方法名
@classmethod
class Dog:
role='狗类'
def test1(self):
'''做一些逻辑操作'''
pass
@classmethod
def test2(cls):
'''cls是参数,指向类对象本身,cls代表了Dog'''
print(cls.role)#
print(Dog.role)#直接使用类名
#Dog是类名也是类对象
print(Dog.role)
#调用类方法
Dog.test2()
#也可以使用对象调用,dog是Dog的子类,在dog中找不到,就去它的父类中去找,所以可以调用
dog=Dog()
dog.test2()
练习:
class Goods:
__discount=1#折扣
def __init__(self,name,price):
self.name=name
self.__price=price
@property
def price(self):
#return self.__price
return self.__price*self.__discount#self --->appleX或者banana,__discount==discount=1,
@classmethod
def change_discount(cls,new_discount):
Goods.__discount=new_discount
#全场八折
Goods.change_discount(0.8)
appleX=Goods('苹果',10)
print(appleX.price)
banana=Goods('香蕉',20)
print(banana.price)