【问题标题】:How do I access instance data from a method in python?如何从 python 中的方法访问实例数据?
【发布时间】:2015-06-29 13:43:40
【问题描述】:

所以我正在尝试创建一个可由 a 类调用的公共方法,以便它编辑 b 类中的数据项。

class aClass():
    def __init__(self):
        aVariable = 1

class aNotherClass():
    def aMethod(self):
        aFunction(5)

def aFunction(aNumber):
    instance1.aVariable = aNumber

instance1 = aClass()
instance2 = aNotherClass()
instance2.aMethod

但是,当我在 aFunction 中调用 instance1 时,python 告诉我它没有定义。如果我想改变aClass中的aVariable,aFunction()应该说什么?

【问题讨论】:

  • 为什么不将instance1 设为aFunction参数?你能提供一个不那么……抽象的例子吗?
  • 你的方法中没有self 参数,所以单独使用aClass() 已经失败了。

标签: python class oop variables edit


【解决方案1】:

我想你在定义类方法时可能会忘记self

参考:https://docs.python.org/2/tutorial/classes.html#class-objects

class aClass():
    def __init__(self):
        aVariable = 1

class aNotherClass():
    def aMethod(self):
        aFunction(5)

def aFunction(aNumber):
    instance1.aVariable = aNumber

instance1 = aClass()
instance2 = aNotherClass()
instance2.aMethod()

【讨论】:

  • 抱歉,我只是输入得太快了。我确实在我的实际代码中包含了 self 参数。我现在修好了。
猜你喜欢
  • 1970-01-01
  • 2021-06-03
  • 2015-07-09
  • 1970-01-01
  • 2023-03-08
  • 1970-01-01
  • 1970-01-01
  • 2012-08-23
  • 1970-01-01
相关资源
最近更新 更多