Python:VB程序员的基本命名耦合集合

2024-09-30 16:20:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在Python上开发我的第一个“Hello World”!很久以前我是Visual Basic程序员

我尝试使用Namedtuple集合,如下所示:

#!/usr/bin/env python3
    
import collections
    
#Tipo da colecao
File = collections.namedtuple('File',['abspath' ,'basename','filextention','filetype'])
Files = []
    
Files.append(File('/home/user/teste1.txt', 'teste1.txt','txt',''))
Files.append(File('/home/user/teste2.txt', 'teste2.txt','txt',''))
Files.append(File('/home/user/teste3.txt', 'teste2.txt','txt',''))
    
for lCtd in range(0,len(Files)):
    print(Files[lCtd].abspath,Files[lCtd].basename,Files[lCtd].filextention)
    
for lCtd in range(0,len(Files)):
    #>>>>>How can I do this?!<<<<< 
    Files[lCtd].filetype = 'A' 

如果有一个最好的方法来做这件事(或所有的代码),我洗耳恭听

非常感谢


Tags: txthomeforfilescollectionsfilefiletypeappend
2条回答

似乎您真正想要的是定义自己的类,如下所示:

class File:
    # make a constructor, with a default parameter (for convenience!)
    def __init__(self, abspath, basename, filextention, filetype = ''):
        self.abspath = abspath
        self.basename = basename
        self.filextention = filextention
        self.filetype = filetype

Files = []

# this part is almost the same, but you don't need the last parameter
# because we gave it a default value    
Files.append(File('/home/user/teste1.txt', 'teste1.txt','txt'))
Files.append(File('/home/user/teste2.txt', 'teste2.txt','txt'))
Files.append(File('/home/user/teste3.txt', 'teste2.txt','txt'))

# this is a better way to loop over a list in Python:
for curFile in Files:
    print(curFile.abspath, curFile.basename, curFile.filextention)

for curFile in Files:
    curFile.filextention = 'A' # in Python all fields are public by default and can be assigned like this

命名元组很有用,但它们是不可变的:它们的属性在创建后不能更改。如果您想要一个类似的方便易变的数据保持器,那么您可能对data classes感兴趣,只要您使用的是Python 3.7或更新版本

from dataclasses import dataclass

@dataclass
class File:
    file_name: str
    abs_path: str
    base_name: str
    file_extension: str
    # The '=' below sets a default value. (You could use '', but None is more
    # commonly used for this.)
    file_type: str =  None

files = [
    File('/home/user/test1.txt', 'test1.txt', 'txt'),
    File('/home/user/test2.txt', 'test2.txt', 'txt'),
    File('/home/user/test3.txt', 'test3.txt', 'txt'),
]
    
for file in files:
    print(file.abs_path, file.base_name, file.file_extension)
    # This will update the file_type attribute for each file:
    file.file_type = 'A'

请注意,在列表(或任何序列)中循环的更具python风格的方法是不依赖len和索引,而只是在项目本身中循环

综上所述,如果您正在寻找一种处理文件的简单方法,例如获取文件名和扩展名,那么您可能还应该看看Pathlib

from pathlib import Path

file = Path('/home/user/test1.txt')
print(str(file), file.name, file.suffix)

# Output: /home/user/test1.txt test1.txt .txt

p.S.file是Python2中的一个内置项,许多编辑器可能仍然会突出显示它本身,但在Python3中用作变量/类名应该是不错的

相关问题 更多 >