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,故也可以由实例来调用。

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

    总结成一张表

    笨鸟先飞
  • 相关阅读:
    java中sleep()和wait()区别
    那些年遇到的坑--------“集合转数组”
    HashMap中推荐使用entrySet方式遍历Map类集合KV而不是keySet方式遍历
    java.util.ConcurrentModificationException 异常原因和解决方法
    java.lang.Exception: No tests found matching
    https和http的主要区别
    交换性别sql
    判断奇偶数
    Jmeter安装使用
    java.io.EOFException: Unexpected EOF read on the socket
  • 原文地址:https://www.cnblogs.com/zoutingrong/p/11892712.html
Copyright © 2011-2022 走看看