0

我正在尝试将以下 Java 代码片段转换为 Python。有人可以帮我解决这个问题。我是 Python 新手。

Java 代码:

public class Person
{
public static Random r = new Random();
public static final int numFriends = 5;
public static final int numPeople = 100000;
public static final double probInfection = 0.3;
public static int numInfected = 0;

/* Multiple experiments will be conducted the average used to
   compute the expected percentage of people who are infected. */
private static final int numExperiments = 1000;

/* friends of this Person object */
private Person[] friend = new Person[numFriends]; ----- NEED TO REPLICATE THIS IN PYTHON 
private boolean infected;
private int id;

我正在尝试将上面标记行中的相同想法复制到 Python 中。有人可以转换“私人人[]朋友=新人[numFriends];” 在python中实现。我正在寻找代码片段...谢谢

4

1 回答 1

1

在我看来,您想知道,Python 中固定长度数组的等价物是什么。哪有这回事。您不必也不能像那样预先分配内存。相反,只需使用一个空列表对象。

class Person(object):
    def __init__(self, name):
        self.name = name
        self.friends = []

然后像这样使用它:

person = Person("Walter")
person.friends.append(Person("Suzie"))       # add a friend
person.friends.pop(0)                        # remove and get first friend, friends is now empty
person.friends.index(Person("Barbara"))      # -1, Barbara is not one of Walter's friends

它的工作原理本质上类似于 Java 中的 List< T >。

哦,Python 中没有访问修饰符(私有、公共等)。一切都是公开的,可以这么说。

于 2013-01-13T20:38:12.643 回答