类方法:
在类里面直接创建的方法,类里面的参数不是
可以通过类名.类方法名,进行调用,
也可以通过对象名.类方法名,进行调用,但是一般不推荐使用
class Student():
def __init__(self):
pass
@classmethod #修饰器
def c_func(cls):
print('我是类方法,不是对象方法')
Student.c_func()
s = Student()
s.c_func()
得到的结果是:
我是类方法,不是对象方法
我是类方法,不是对象方法
Process finished with exit code 0
类方法创建时一定要注意,在类方法前一定要加上@classmethod,这表示修饰器,下面是类的方法。而且可以在一个类里面写多个类方法,但是每一个类方法前都要加上修饰器@classmethod
如:
class Student():
@classmethod # 方法解释器
def stu_fun(cls):
print("I come from class Student")
@classmethod
def stu_fun2(cls,a,b):#cls表示当前类,可以用别的单词代替,只不过为了提高代码的可读性,默认是cls
if a>b:
print(a)
else:
print(b)
Student.stu_fun()
Student.stu_fun2(2,3)
得到的结果:
I come from class Student
3
Process finished with exit code 0
特别注意的是:
类的方法不可以调用实例方法或者实例变量:因为在类方法内部不存在对象名
但是实例方法可以调用类方法或者类变量:可以但是不建议这么使用
静态方法:
既不属于类也不属于对象,就是一个普通方法,里面没有默认的参数
构建静态方法如下:需要注意,在方法前面加上@staticmethod
@staticmethod
def static_fun():
面向对象的组合用法:
组合指的是:在一个类中以另外一个类的对象作为数据属性,称为类的组合
设计思路:一个学生会一个一部手机,学生使用手机看电影
定义两个的对象一个学生类,一个手机类,通过两个类创建两个对象,学生对象访问手机对象,并且使用手机对象的方法
class Student():
#定义一个学生类
def __init__(self,name,age,grade):
self.name = name
self.age = age
self.grade = grade
self.phone = Phone('HuaWei','rad')
#学生对象访问手机对象
def stu_funing(self):
pass
class Phone():
def __init__(self,brand,color):
self.color = color
self.brand = brand
def phone_funing(self,fun1,fun2):
self.fun1 = fun1
self.fun2 = fun2
choose = input("请输入您的选项:")
if str(fun1) == choose:
print("看电影")
elif str(fun2)==choose:
print("听音乐")
s = Student('刘美',28,'三(一)班')#通过类创建一个学生对象
s.phone.phone_funing(1,2)#通过学生对象访问手机对象,并且使用手机对象的方法phone_funing
输出结果:
D:********************************面向对象之类的组合.py
请输入您的选项:1
看电影
Process finished with exit code 0