如何访问方法的属性

时间:2013-05-23 14:36:54

标签: python class python-2.7

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

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'

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

3 个答案:

答案 0 :(得分:4)

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

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'

答案 1 :(得分:2)

在您不致电my_text之前,

show_text属性不存在:

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

如果您希望在实例创建期间创建属性,请将它们放在__init__方法中。

答案 2 :(得分:2)

你的第一个例子不起作用:因为你从不使用show_text()方法,你的对象永远不会有属性my_text(只有当你调用那个方法时才会“添加”到你的对象)

第二个例子很好,因为只要对象被实例化就会执行__init__方法。

此外,通过对象本身的getter方法访问对象属性是一个很好的做法,因此修改代码的最佳方法是

class Test1:
    def __init__(self,value):
        self.my_text = value
    def show_text(self):
        return self.my_text

然后以这种方式使用

t = Test1('hello')
t.show_text()

最后,有一个像这样的方法也很好

def set_text(self,new_text):
    self.my_text = new_text