class Message_Board:
def __init__(self,name):
self.messages = []
def add_message(self, message=None, text='', author='Unknown'):
if(message == None):
self.messages = Message(text, author) ###
else:
self.messages.append(message) ###
我在使用add_message
方法时遇到问题,特别是我标记为###
的两行。我希望能够向self.messages添加一个消息对象,使用的能够以两种不同的方式放置消息。如果传入消息对象,则应忽略文本和作者,但如果未传入对象,则应使用文本和作者创建新对象。我不想更改原始def add_message()
行。
答案 0 :(得分:0)
在两种情况下都使用class Message_Board:
def __init__(self,name):
self.messages = []
def add_message(self, message=None, text='', author='Unknown'):
if message is None:
self.messages.append(Message(text, author))
else:
self.messages.append(message)
:
// Population
var Gene = function(text){
if(text){
this.text = text;
}
};
Gene.fitness = 0;
Gene.generation = 0;
var word = new Gene('Hello');
// This is where it crashes!!
// Make elements
var genArr = [];
var population = 20;
var mutation = 0;
for(var i = 0; i < population; i++){
var gene = "";
var abc = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var j = 0; i < word.text.length; j++) {
var element = abc.charAt(Math.floor(Math.random() * abc.length));
gene += element;
}
genArr.push(gene);
}
// Divide them - fitness
// 1/20 - 0.05% each
var fitElements = [];
for (var i = 0; i < genArr.length; i++) {
var score = 0;
var curWord = Array.from(genArr[i]);
for (var j = 0; j < word.text.length; j++) {
if(genArr[j].substr(j, 1) == word.text.substr(j, 1)){
score += 1;
}
}
if(score > 0){
fitElements.push([genArr[i], (score * (1 / population)) ** 2]);
}
}
for (var i = 0; i < fitElements.length; i++) {
console.log('Element: ' + fitElements[i][0] + ', Score: ' + fitElements[i][1]);
}