每个python对象都有一个int

每个python对象都有一个int

本文介绍了每个python对象都有一个int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

I想要像Python中的以下Java类:

I want to something like the following Java class in Python:

public class MyObject {
    private static int ID = 0;
    private final int id;
    public MyObject() {
        id = ID++;
    }
}

在这个Java代码中,每个 myObject 将具有 id ,并且两个对象无法具有相同的ID(它是单线程应用程序)。

In this Java code, every myObject will have id and there will be no way that two objects could have the same ID (it's a one-threaded application).

我可以在Python中做这样的事情吗?

Can I do something like this in Python?

推荐答案

在Python中,你可以直接引用class属性:

In Python, you can just refer directly to the class attribute:

class MyObject(object):
    ID = 0

    def __init__(self):
       self.id = MyObject.ID = MyObject.ID + 1

演示:

>>> class MyObject(object):
...     ID = 0
...     def __init__(self):
...        self.id = MyObject.ID = MyObject.ID + 1
...
>>> MyObject().id
1
>>> MyObject().id
2
>>> MyObject().id
3
>>> MyObject.ID
3

这篇关于每个python对象都有一个int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 17:37