我正在尝试将以下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。我正在寻找代码片段...谢谢
答案 0 :(得分: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
它基本上像List< T>在Java。
哦,Python中没有访问修饰符(私有,公共等)。一切都是公开的,可以说。