【问题标题】:Can you access attributes that were created with the init method from other methods in the class? [closed]您可以从类中的其他方法访问使用 init 方法创建的属性吗? [关闭]
【发布时间】:2021-08-20 02:24:42
【问题描述】:

当我编写__init__ 方法并分配属性时,我可以在我在该类中编写的其他方法(函数)中访问这些属性吗?如果是这样,它是如何完成的?

我用谷歌搜索了这个但找不到答案。我一直无法理解这个。

【问题讨论】:

  • ...如果您发布了您一直在尝试但不起作用的代码,这会更清楚,因此我们可以看到您哪里出错了。
  • 查看self关键字
  • @RoboMop self 不是关键字
  • “当我编写 init 方法并分配属性时,我可以在我在该类中编写的其他方法(函数)中访问这些属性吗?”当然可以,这就是属性的全部意义。 “如果是这样,它是怎么做到的?”与您始终访问属性的方式相同。
  • @RoboMop self 不是关键字。它只是传统上赋予方法中第一个位置参数的名称,当在实例上调用方法时,它将隐式传递给实例

标签: python python-3.x class oop methods


【解决方案1】:

当你创建一个类并设置一个实例(如first_class = MyClass())时,def __init__(self): 会运行或初始化。那里的任何变量,例如self.name,都可以从类及其函数中访问,也可以在您在另一个程序中使用类时访问。 self 有点将该变量附加到该类。 基本上使用 Allure 的例子:

class MyClass:
    def __init__(self):
        self.name = "John"
    def show_name(self):
        print(self.name)

然后在课程之外的程序中使用MyClass的名字:

firstClass = MyClass()#Initialise MyClass and its variables
print(firstClass.name)

或者:

firstClass= MyClass()
firstClass.show_name()

两个输出:

'John'

(仍然为其他人提供这个答案,希望你不介意:))

【讨论】:

    【解决方案2】:

    使用self:

    class MyClass:
        def __init__(self):
            self.name = 'John'
        def other_method(self):
            print(self.name)
    

    other_method 将打印“John”。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-12
      相关资源
      最近更新 更多