如何确保属性值在Python中是唯一的?

时间:2015-08-06 14:50:12

标签: python oop python-3.x uniqueidentifier

我在抓一个包含人员列表的网站。同一个人可以出现不止一次,并且多个人可以共享相同的名称:

Tommy Atkins (id:312)
Tommy Atkins (id:183)
Tommy Atkins (id:312)

我想为每个人创建一个对象并丢弃重复项。

我目前正在使用列表推导来遍历所有类实例,并查看key是否已被使用。有没有更简单的方法呢?

class Object:
    def __init__(self, key):
        if [object for object in objects if object.key == key]:
            raise Exception('key {} already exists'.format(key))
        else: self.key = key

objects = []
objects.append(Object(1))
objects.append(Object(1)) # Exception: key 1 already exists

2 个答案:

答案 0 :(得分:1)

在您的班级中定义__eq____hash__,根据DESC, 的值比较实例,并使用它计算哈希值。而不是列表使用.,因为它会以有效的方式自动过滤重复项:

DESC
LIMIT 1;

不要将实例永久分配给变量,否则不会进行垃圾回收(请注意,这仅适用于CPython):

MyFragment

<强>输出:

public class Home_Map extends Fragment {

 GoogleMap googleMap;
 FragmentManager myFragmentManager;
 SupportMapFragment mySupportMapFragment;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // TODO Auto-generated method stub
     View rootView = inflater.inflate(R.layout.fragment_home__map, container, false);

     //googleMap.setMyLocationEnabled(true);

        try {
            // Loading map
            initilizeMap();
            googleMap.setMyLocationEnabled(true);

        } catch (Exception e) {
            e.printStackTrace();
        }
    return rootView;
}
 private void initilizeMap() {

        try
        {
        if (googleMap == null) {
            myFragmentManager = getFragmentManager();
            mySupportMapFragment = (SupportMapFragment)myFragmentManager.findFragmentById(R.id.map2);
            googleMap = mySupportMapFragment.getMap();

            if (googleMap == null) {
                Toast.makeText(getActivity().getApplicationContext(),
                        "Sorry! unable to create maps", Toast.LENGTH_SHORT)
                        .show();
            }
        }
        } catch (Exception e) { Toast.makeText(getActivity().getApplicationContext(), ""+e, 1).show();
            // TODO: handle exception
        }
    }

   @Override
    public void onResume() {
        super.onResume();

        initilizeMap();

    }

   @Override
    public void onDetach() {
        // TODO Auto-generated method stub
        super.onDetach();
          try {
                Field childFragmentManager = Fragment.class
                        .getDeclaredField("mChildFragmentManager");
                childFragmentManager.setAccessible(true);
                childFragmentManager.set(this, null);

            } catch (NoSuchFieldException e) {
                throw new RuntimeException(e);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
    }

    }

答案 1 :(得分:0)

您的ID的全局存储空间很好,但最好使用set代替list,因为检查i in {}是O(1)而i in []是{0} O(N)