Skip to main content
 首页 » 编程设计

python之如何访问方法的属性

2025年05月04日11虾米哥

是否可以直接访问方法的属性?我试过了,但失败了:

class Test1: 
    def show_text(self): 
        self.my_text = 'hello' 

结果是:

>>> t = Test1() 
>>> t.my_text 
Traceback (most recent call last): 
  File "<stdin>", line 1, in <module> 
AttributeError: Test1 instance has no attribute 'my_text' 

我发现使用它可以使它工作:

class Test1: 
    def __init__(self): 
        self.my_text = 'hello' 

但我想知道是否仍然可以直接访问方法的属性?还是我在做一些非常糟糕的事情?

请您参考如下方法:

实例变量是在对象被实例化后创建的,并且只有在它们被分配给之后才创建。

class Example(object): 
      def doSomething(self): 
          self.othervariable = 'instance variable' 
 
>> foo = Example() 
>> foo.othervariable 
AttributeError: 'Example' object has no attribute 'othervariable' 

因为 othervariable 是在 doSomething 中赋值的——我们还没有调用它——所以它不存在。

不过,一旦我们调用它:

>> foo.doSomething() 
>> foo.othervariable 
'instance variable' 

__init__ 是一种特殊的方法,只要类实例化发生,它就会自动被调用。这就是为什么当您在其中分配变量时,它可以在您创建新实例后立即访问。

class Example(object): 
 
      def __init__(self): 
          self.othervariable = 'instance variable' 
 
>> foo = Example() 
>> foo.othervariable 
'instance variable'