zoukankan      html  css  js  c++  java
  • Python3-面向对象-四种方法

    类中方法:动作
    种类:①普通方法 ②类方法 ③静态方法 ④魔术方法
     
    ① 普通方法:
            def 方法名(self[,参数1,参数2...])
                pass
     1 class Student:
     2     def __init__(self,name,age):
     3         self.name = name
     4         self.age = age
     5 
     6     def call(self):     # 普通方法
     7         print("{} 今年 {} 岁了!".format(self.name,self.age))
     8 
     9     def food(self,food):    # 普通方法
    10         print("{} 最爱吃 {} 了!".format(self.name,food))
    11 
    12 
    13 s = Student('XiaoMing',18)
    14 s.call()
    15 s.food('巧克力')
    结果:

    XiaoMing 今年 18 岁了!
    XiaoMing 最爱吃 巧克力 了!

     
    ② 类方法:
            1.定义需要依赖装饰器@classmethod
            2.类方法中参数不是一个对象,而是类
            3.类方法中只可以使用类属性
            4.类方法中不能使用普通方法
        
        作用:
            因为只能访问类属性和类方法,所以可以在对象创建之前,如果需要完成一些功能(动作)
     1 class Student:
     2     def __init__(self,name,age):
     3         self.name = name
     4         self.age = age
     5 
     6     def call(self):
     7         print("{} 今年 {} 岁了!".format(self.name,self.age))
     8 
     9     @classmethod    # 类方法
    10     def run(cls):
    11         print(cls)      # <class '__main__.Student'>
    12         print("---类方法---")
    13 
    14 s = Student('XiaoMing',18)
    15 s.call()
    16 s.run()

    结果:

    XiaoMing 今年 18 岁了!
    <class '__main__.Student'>
    ---类方法---

     
    ③ 静态方法:
            1.需要装饰器@staticmethod
            2.静态方法无需传递参数(cls、self)
            3.只能访问类的属性和方法,无法访问对象的属性和方法
            4.加载时机同类方法
     1 class Person:
     2     __age = 20
     3 
     4     def __init__(self):
     5         self.name = 'Seele'
     6 
     7 
     8     @staticmethod
     9     def show_age():
    10         print("----->",Person.__age)
    11 
    12 Person.show_age()

    结果:-----> 20

     
    ④ 魔术方法:
             魔术方法就是一个类/对象中的方法,和普通方法唯一的不同时,普通方法需要调用!而魔术方法是在特定时刻自动触发。
            格式:__名字__() --> 称之为魔术方法
     
    总结:
        类方法 静态方法
     
        不同:1.装饰器不同
              2.类方法是有参数的,静态方法没有参数
     
        相同:1.只能访问类的属性和方法,无法访问对象的属性和方法
              2.都可以通过类名调用访问
              3.都可以在创建对象之前使用,因为是不依赖于对象
     
        普通方法 与 两者区别:
        
        不同:1.没有装饰器
              2.普通方法永远依赖对象,因为每个普通方法都有一个self
              3.只有创建了对象才可以调用普通方法,否则无法访问
     
  • 相关阅读:
    el-select下拉框选项太多导致卡顿,使用下拉框分页来解决
    vue+elementui前端添加数字千位分割
    Failed to check/redeclare auto-delete queue(s)
    周末啦,做几道面试题放松放松吧!
    idea快捷键
    解决flink运行过程中报错Could not allocate enough slots within timeout of 300000 ms to run the job. Please make sure that the cluster has enough resources.
    用.net平台实现websocket server
    MQTT实战3
    Oracle 查看当前用户下库里所有的表、存储过程、触发器、视图
    idea从svn拉取项目不识别svn
  • 原文地址:https://www.cnblogs.com/DemonKnifeGirl/p/12997382.html
Copyright © 2011-2022 走看看