简体   繁体   English

在Python中引用实例属性的快捷方式

[英]Shorthand way to refer to instance attributes in Python

I have a Python class that contains many variables, along the lines of: 我有一个Python类,其中包含许多变量,大致如下:

class file:
    def __init__(self, name)
        self.name = name
        self.size = None
        self.num_lines = None
        self.directory = None
  • Note that this is just an example - my real class has very descriptive (and therefore long) names and many more members 请注意,这仅是一个示例-我的真实类具有非常描述性的名称(因此很长),并且成员更多

After I create an instance, I have to assign values to those variables: 创建实例后,必须为这些变量分配值:

f = file("abc.txt")
f.size = get_file_info(f.name)
f.num_lines = count_lines(f.name)
f.directory = get_dir(f.name)
f.new_name = root + f.directory + f.name + f.size

What I'd really like is the syntactic sugar of a using keyword: 我真正想要的是using关键字的语法糖:

f = file("abc.txt")
using f:
    size = get_file_info(name)
    num_lines = count_lines(name)
    directory = get_dir(name)
    new_name = root + directory + name + size

That is, I want to provide a new context in which variables will be searched for first, before Python does all the rest of its searches. 也就是说,我想提供一个新的上下文,在该上下文中,将在Python执行所有其余搜索之前首先搜索变量。

Is there anything like this? 有没有这样的东西? If not, it seems like a useful addition to the language. 如果没有,这似乎是对该语言的有用补充。

Edit: Per the answers, I deliberately don't want to do this inside the init function. 编辑:根据答案,我故意不想在init函数中执行此操作。 For personal reasons. 由于个人原因。 Not really - it just doesn't make sense in my use case 并非如此-在我的用例中这没有意义

All the code you want to put in a using block should be handled by your class's __init__ method. 您要放入using块中的所有代码都应由类的__init__方法处理。

class File:
    def __init__(self, name)
        self.name = name
        self.size = get_file_info(name)
        self.num_lines = count_lines(name)
        self.directory = get_dir(name)
        self.new_name = os.path.join(root, self.directory, self.name, self.fize)

f = File("abc.txt")

Some of the functions you imply ( get_file_info , etc.) may be more suited to being methods of the File class, rather than standalone functions that take a file name as an argument. 您暗示的某些函数( get_file_info等)可能更适合作为File类的方法,而不是将文件名作为参数的独立函数。

There is no support in the language for this. 语言对此没有支持。 You can only create variable namespaces by functions and modules. 您只能按功能和模块创建变量名称空间。 Not even with classes (that's why, even inside a class, you have to use self to refer to its attributes) 甚至没有类(这就是为什么,即使在类内部,也必须使用self来引用其属性)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM