实现类概念在python中不起作用

实现类概念在python中不起作用,python,Python,方案1:基于功能的:- import xml.etree.ElementTree as ET import sys doc = ET.parse("users.xml") root = doc.getroot() root_new = ET.Element("users") for child in root: username = child.attrib['username'] password

方案1:基于功能的:-

import xml.etree.ElementTree as ET
import sys   
doc       = ET.parse("users.xml")
root      = doc.getroot()
root_new  = ET.Element("users") 
for child in root:
    username             = child.attrib['username']
    password             = child.attrib['password']   
    # create "user" here
    user    = ET.SubElement(root_new, "user") 
    user.set("username",username)               
    user.set("password",password) 
    #checking attribute for skipping KeyError
    if 'remote_access' in child.attrib:
        remote_access   = child.attrib['remote_access']
        user.set("remote_access",remote_access) 
    for g in child.findall("group"):
        # create "group" here
        group     = ET.SubElement(user,"group")  
        if g.text != "lion":
            group.text = g.text 
tree = ET.ElementTree(root_new)
tree.write(sys.stdout)
这是xml:-

<users>
<user username="admin"  password="admin" remote_access="yes"></user>
<user username="private_user1" password="user1" ><group>group1</group><group>group2</group></user>
<user username="private_user2" fullname="user2" password="user2"><group>group1</group><group>group2</group></user>
</users>
如何通过面向对象的概念类更好地实现这一点。我的类实现根本不起作用。请帮帮我(


我需要将上面的代码转换成Python类:这就是要求:(

您有一个缩进问题(在
print
语句后的所有内容都缩进了一级)


告诉你的老师把随机代码改写成“类”这是一个毫无意义的要求。像这样的代码不需要Python中的类。

你似乎对类了解不多,我建议你读一本关于这个主题的书,即使有人会为你实现它,在你理解基本知识之前,它对你也没有多大用处。目前,这个类是完全有用的less(即使它能工作)谁是那个人?谁将实施:(无论如何,谢谢你的书顺便说一句,你的“函数实现”离“函数实现”一点也不近此外,你还必须学习Python的一个非常基本的东西,以使任何东西都能从那里开始工作——我建议在开始之前做一些练习。老师问我,她在课堂上需要它:(做什么
import xml.etree.ElementTree as ET
import sys

class users_detail (object):

    def __init__( self, xml_path ):
     """bla bla
     """
    try:
        doc = ET.parse("users.xml")
    except:
        print 'xml not found' 
        root      = doc.getroot() 
        root_new  = ET.Element("users") 
        for child in root:
            username             = child.attrib['username']
            password             = child.attrib['password']
            user    = ET.SubElement(root_new, "user") 
            user.set("username",username)               
            user.set("password",password) 
            if 'remote_access' in child.attrib:
                remote_access   = child.attrib['remote_access']
            for g in child.findall("group"):
                group     = ET.SubElement(user,"group")  
                if g.text != "lion":
                    group.text = g.text 
        tree = ET.ElementTree(root_new)
        tree.write(sys.stdout)
if __name__=='main':
    users_detail()