【问题标题】:How do I reference the object passed to my class when I instantiate?实例化时如何引用传递给我的类的对象?
【发布时间】:2013-08-06 20:58:37
【问题描述】:

我有这门课

class SECHeader(object):
    def __init__(self,header_path):
        self.header = open(header_path).read()

我在这个类中有一些方法,我尝试做的方法之一需要解析名称

        def parsed_name(self):
            return header_path.split('-')[-1]

如果在我的代码中我使用名称 header_path 来识别我要操作的东西,这很好用

for header_path in header_paths:
       header = SECHeader(header_path)
       print header.parsed_name()

如果我改名

for named_path in header_paths:
       header = SECHeader(named_path)
       print header.parsed_name()

我得到一个名称错误

我玩过——如果可以在 parsed_name 函数中为对象使用任何名称,只要我为要处理的对象使用相同的名称,但我似乎无法弄清楚如何命名它,所以用户不必使用我的命名方案

特别是如果我将 parsed_name 函数更改为

        def parsed_name(self):
            return banana.split('-')[-1]

如果在我的循环中将其更改为

for banana in header_paths:
    header = SECHeader(banana)
    print header.parsed_name()

它就像一个魅力,但这限制了我正在研究的这个东西的便携性。因为任何用户都必须使用我在函数中使用的任何标签来引用路径。

【问题讨论】:

    标签: python class namespaces


    【解决方案1】:

    这里的问题是您将 header_path 声明为 init 函数的变量。它的作用域是 init 函数的本地。

    您需要将 header_path 关联为类实例的变量。

    Class SECHeader(object):
        def __init__(self,header_path):
            self.header_path = header_path # Instantiate a variable for class object
            self.header = open(header_path).read()
    
        def parsed_name(self):
            return self.header_path.split('-')[-1] # Call the associated variable
    

    另一种方法是在 parsed_name 中实际调用您作为参数提供给 SECHeader 的变量。这个变量名将在类命名空间中。

    for banana in header_paths:
        header = SECHeader(banana)
        print header.parsed_name()
    
    Class SECHeader(object):
        def __init__(self,header_path): # header_path takes value of banana
                                        # and ends scope in __init__
            self.header = open(header_path).read()
    
        def parsed_name(self):
            return banana.split('-')[-1] # banana was passed to class and is known
    

    【讨论】:

      猜你喜欢
      • 2022-10-24
      • 1970-01-01
      • 2015-01-15
      • 1970-01-01
      • 2013-04-30
      • 1970-01-01
      • 1970-01-01
      • 2012-07-21
      • 1970-01-01
      相关资源
      最近更新 更多