Good Style in Python Objects

后端 未结 5 1063
春和景丽
春和景丽 2021-01-19 23:42

Most of my programming prior to Python was in C++ or Matlab. I don\'t have a degree in CS (almost completed a PhD in physics), but have done some courses and a good amount o

5条回答
  •  旧时难觅i
    2021-01-20 00:23

    The more pythonic way is to avoid tedious objects if you don't have to.

    class UnionFind(object):
        def __init__(self, members=10, data=None):
            """union-find data structure for Kruskal's algorithm
            members are ignored if data is provided
            """
            if not data:
                self.data = [self.default_data() for i in range(members)]
                for d in self.data:
                    d.size   = 1
                    d.leader = d
                    d.next   = None
                    d.last   = d
            else:
                self.data = data
    
        def default_data(self):
            """create a starting point for data"""
            return Data(**{'last': None, 'leader':None, 'next': None, 'size': 1})
    
        def find(self, element):
            return element.leader
    
        def union(self, leader1, leader2):
            if leader2.leader is leader1:
                return
            if leader1.size >= leader2.size:
                newleader = leader1
                oldleader = leader2
            else:
                newleader = leader2
                oldleader = leader1
    
            newleader.size = leader1.size + leader2.size
    
            d = oldleader
            while d is not None:
                d.leader = newleader
                d = d.next
    
            newleader.last.next = oldleader
            newleader.last = oldleader.last
    
            oldleader.size = 0
            oldleader.last = None
    
    class Data(object):
        def __init__(self, **data_dict):
            """convert a data member dict into an object"""
            self.__dict__.update(**data_dict)
    

提交回复
热议问题