【问题标题】:How can i take python self class attributes in class's method?如何在类的方法中获取 python 自类属性?
【发布时间】:2020-02-17 17:21:31
【问题描述】:

我从 Python 的类开始,我想做这样的事情:

class First:
    def __init__(self):
        self.value = 1

    @classmethod
    def func(cls):
        print(self.value)


second = First()
second.func()

但我无法访问班级的self.value。有人可以帮帮我吗?

【问题讨论】:

  • 当使用classmethod时,你想通过cls而不是self。但是类方法不能也不应该依赖于实例的状态。 stackoverflow.com/questions/12179271/…
  • @classmethods 取cls,这是类。如果你想使用 self 这是对象实例,请移除装饰器。

标签: python class methods attributes


【解决方案1】:

IIUC 那么你的类应该如下所示:

class First:
    value = 1

    @classmethod
    def func(cls):
        print(cls.value)

【讨论】:

    【解决方案2】:

    @classmothod 有必要吗?
    如果被淘汰,则该类运行良好。

    class First:
        def __init__(self):
            self.value = 1
    
        def func(self):
            print(self.value)
    
    second = First()
    second.func()
    

    【讨论】:

      【解决方案3】:

      如果你只想在你的类中创建一个函数并使用 self 参数,那就这样做吧:

      class First:
          def __init__(self):
              self.value = 1
      
          def func(self):
              print(self.value)
      
      
      second = First()
      second.func()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-03-26
        • 2019-05-20
        • 2019-02-01
        • 2020-01-30
        • 1970-01-01
        • 1970-01-01
        • 2022-11-25
        相关资源
        最近更新 更多