• 技术文章 >常见问题 >Python常见问题

    python静态方法怎么使用self

    silencementsilencement2019-10-25 16:21:50原创3008

    python - 静态方法,类方法,属性方法

    静态方法实际上与类(或者实例)没有什么关系。
    使用了静态方法,则不能像实例方法那样再使用self。

    装饰器

    1

    2

    3

    @staticmethod  # 静态方法

    @classmethod  # 类方法

    @property   # 属性方法

    静态方法可以使用类调用也可以使用对象调用:

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    class Dog(object):

        def __init__(self, name):

            self.name = name

     

        @staticmethod

        def eat():

            print(" is eating ")

     

    # 类调用

    Dog.eat()

     

    # 对象调用

    d = Dog('dog1')

    d.eat()

    静态方法:
    只是名义上归类管理,实际上在静态方法里面访问不了类或者实例的任何属性。 一般不需要传参数self。

    类方法
    只能访问类变量,不能访问实例变量。需要有self参数。

    类方法的示例:

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    class Dog(object):

     

        food2 = "food2"

     

        def __init__(self, name):

            self.name = name

        @classmethod

        def eat(self):

            print(" is eating %s " %self.food2)

     

    Dog.eat()

    d = Dog('dog1')

    d.eat()

     

    或者这样:

     

    class Dog(object):

        food2 = "food2"

        def __init__(self, name):

            self.name = name

        @classmethod

        def eat(cls):

            print(" is eating %s " %cls.food2)

     

    Dog.eat()

    d = Dog('dog1')

    d.eat()

    属性方法:
    把一个方法变成一个静态属性。调用的时候不需要加()。使用属性方法代替setter和getter方法

    1

    2

    3

    4

    5

    6

    7

    8

    9

    class Dog(object):

        def __init__(self, name):

            self.name = name    @property

        def eat(self):

           # print("I am eating")

            return 'eat'

     

        def abc(self):

            print('abc')d = Dog('xg')print (d.eat)

    更多学习内容,请点击python学习网

    专题推荐:self
    上一篇:python和php选哪个 下一篇:python怎么打开命令行窗口

    相关文章推荐

    • python切片步长负数怎么理解• python导入不了模块怎么办• python用什么软件执行程序• python 怎么调用js• python怎么退出程序

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网