擅长:python、mysql、java
<p>如果要确保每个对象在所有实例中都有唯一的编号,则需要让每个实例对照<code>class</code>级别<code>set</code>检查生成的值,以确保唯一性。你知道吗</p>
<pre><code>import random as random
class MyClass:
class_random_set = set()
def __init__(self, lengthOfList):
self.my_random_set = set()
for _ in range(0, lengthOfList):
while True:
num = random.uniform(-1.0, 1.0)
if num not in self.class_random_set:
self.class_random_set.add(num)
self.my_random_set.add(num)
break
a = MyClass(2) #make a set with 2 random numbers
b = MyClass(1) #make a set with 1 random number
print(a.my_random_set)
print(b.my_random_set)
</code></pre>