【问题标题】:How to acces class variables outside class in python如何在python中访问类外的类变量
【发布时间】:2015-03-25 02:31:45
【问题描述】:

我是 python 新手,这是我在 python 中的第一个程序,我想知道如何访问类外部的类变量。我有一个会引发一些错误的代码

from xxxxxxx import Products

class AccessKey(object):
    def key(self):
        self.products = Products(
           api_key = "xxxxxxxxxxxxxxxxxxxxxx",
           api_secret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
        )

class Data(AccessKey):
    def Print(self):
        products.products_field( "search", "Samsung Galaxy" )
        results = products.get_products()
        print "Results of query:\n", results

data = Data()
data.Print()

上面的程序抛出以下错误

Traceback (most recent call last):
  File "framework.py", line 10, in <module>
    class Data(AccessKey):
  File "framework.py", line 13, in Data
    results = products.get_products()
NameError: name 'products' is not defined

【问题讨论】:

    标签: python class variables scope


    【解决方案1】:

    首先,您需要将 products 字段称为 self.products. (等等)

    看起来您不必在调用“产品”之前对其进行实例化。如果你想确保它被实例化,那么你需要在父类的构造函数中设置产品(AccessKey)

    一个简化的例子是:

    class A (object):
        def __init__ (self):
            self.x = 1
    
    class B (A):
        def get (self):
            return self.x
    
    b = B ()
    print (b.get ())
    

    基本上,您必须将以下构造函数添加到您的第一个类中

    class AccessKey(object):
        def __init__(self):
            self.products = Products (X, Y) # or whatever you want to initialize it to
        # the rest of your code below
    

    或者,你可以做得更好,创建一个 set_product 函数:

    # inside of the parent class
        def set_product (self, X, Y):
            try:
                self.products.product_field (X, Y)
            except NameError:
                self.products = Product (X, Y)
    

    【讨论】:

      【解决方案2】:

      Data 类继承自 AccessKey。所以Data可以使用类属性products,但是需要通过

      self.products.products_field(...) 而不是products.products_field(...)。 同样,应该是results = self.products.get_products()

      但请注意,实例属性 products 仅在调用 key 方法时设置,因此在调用 key 方法之前,您将获得NameError,即

      data = Data()
      data.key()
      data.Print()
      

      另外,在 python 中,不鼓励使用 getter 和 setter,并且对代码格式指南施加了很大的压力。在您的代码中,类方法应该小写,但是因为print 会隐藏一个保留字,所以最好使用print_ 之类的东西。

      【讨论】:

        猜你喜欢
        • 2021-07-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-02-15
        • 2015-04-06
        • 2017-04-22
        • 1970-01-01
        相关资源
        最近更新 更多