zoukankan      html  css  js  c++  java
  • python 方法

    1:对象方法:

    对象方法分为共有方法和私有方法两种.

    公有方法:

    class people:

      def sayhi(self):

        print("hello,how are you?")

    p = people()

    print(p.sayhi())#输出为hello,how are you?

    私有方法:

    class people:

      def __sayhi(self):

        print("hello,how are you?")

      def output(self):##通过self进行调用

        self.__sayhi()#通过self进行调用

    p = people()

    print(p.output())

    ##s私有方法不能通过对象名进行调用,只能在公有方法中通过self进行调用!

    类方法

    类方法属于类,通过python的修饰器@classmethod实现,类方法只能通过类名进行调用具有cls参数

    类方法举例:

    class country:

      @classmethod

      def   classMethod(cls):

        print("china is my country!")

    print(people.classMthod())

    输出:china is my country!

    ##类方法只能通过类名进行调用!!

    静态方法

    静态方法属于类,通过python的修饰器@staticmethod实现,静态方法只能通过类名调用,静态方法中不能访问属于对象的成员,只能访问属于类的成员。

    静态方法举例:

    class people:

      number = 10

      @staticmethod

      def    getnumber():

        return number

      @staticmethod

      def   setnumber(n):

        people.number = n

    print(people.getnumber())

    people.setnumber(1000)

    print(people.getnumber())

     输出结果:

    10

    1000

    总结:

    对象方法只能通过实例调用,类不能调用

    类方法可以由类调用,而且因为传入了参数cls,故也可以由实例来调用。

    静态方法既能通过实例调用也能通过类来进行调用

    总结成一张表

    笨鸟先飞
  • 相关阅读:
    MyBatis基础面试题
    MyBatis面试题
    Spring MVC @RequestBody自动转JSON HTTP415错误解决方法
    【GDKOI 2016】地图 map 类插头DP
    【Codechef FRBSUM】【FJOI2016】【BZOJ4299】【BZOJ 4408】 可持久化线段树
    【NOI2005】聪聪和可可 概率与期望 记忆化搜索
    【bzoj 1076】【SCOI2008】奖励关
    BZOJ 1009 HNOI 2008 GT考试 递推+矩乘
    BZOJ 3809 Gty的二逼妹子序列
    BZOJ 2821作诗(Poetize) 分块
  • 原文地址:https://www.cnblogs.com/zoutingrong/p/11892712.html
Copyright © 2011-2022 走看看