python - 实例化时如何引用传递给我的类的对象?

标签 python class namespaces

我有这个类

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()

我收到一个 NameError

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

特别是如果我将 parsed_name 函数更改为
        def parsed_name(self):
            return banana.split('-')[-1]

在我的循环中,如果将其更改为
for banana in header_paths:
    header = SECHeader(banana)
    print header.parsed_name()

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

最佳答案

这里的问题是您将 header_path 声明为 的变量。初始化 功能。它的范围是本地的 初始化 功能。

您需要的是将 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

关于python - 实例化时如何引用传递给我的类的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18090364/

相关文章:

python - Numpy,连接整数和 ndarrays 的简单公式

c++ - 如何在两个不同的命名空间(但只写一次)中使用不同的命名空间实现来定义相同的头文件?

ruby - Ruby 中命名空间的不同方式

c++ - 不连续的嵌套命名空间

python - 我可以同时使用 uwsgi + (tornado, gevent, etc) 吗?

python - python中的操作数无法一起广播错误

python 否定搜索

excel - 如何正确使用 VBA 类模块集合?

python - 使用类作为另一个类的方法的装饰器

ios - Object C 到 Swift 自定义类的实现