【18/09/10】关于len()和__len__()的一点小测试

在廖雪峰网站上获取对象信息章看到len()函数等价于__len__()方法,并且在我们自己定义的类里面,可以通过自己定义__len__()方法,然后通过len()函数来调用,有点疑惑,因此做一点小测试。

class MyDog(object):
    def __len__(self):
        return 100

dog = MyDog()
print(len(dog))

输出结果为100

疑问:是否任意字段都可以如此等价?将len改为saber试试,

class MyDog(object):
    def __saber__(self):
        return 100

dog = MyDog()
print(saber(dog))

 结果异常,

F:\pROGramming\pYthon\python.exe C:/Users/boTTle/PycharmProjects/Ironac/test.py
Traceback (most recent call last):
  File "C:/Users/boTTle/PycharmProjects/Ironac/test.py", line 6, in <module>
    print(saber(dog))
NameError: name 'saber' is not defined

Process finished with exit code 1

故此猜想,应该是内建函数len()的逻辑就是调用str方法str.__len__(),而在用户自定义__len__()之后,原方法逻辑被替换,但len()逻辑不变,因此可以如此等价替换,且仅限于该关键字。

遗传算法是一种模拟自然进化过程的优化算法,主要用于解决复杂的优化问题。在遗传算法中,通过对个体(解)进行基因操作(交叉、变异等),不断地产生新的个体,并通过选择机制,筛选出适应度高的个体,从而逐步优化得到最优解。 下面是一个简单的遗传算法的Python实现代码: ```python import random # 定义适应度函数 def fitness(individual): # 适应度函数为 x^2 的形式,其中 x 为个体的染色体长度 return sum([gene**2 for gene in individual]) # 初始化种群 def init_population(pop_size, gene_size): population = [] for i in range(pop_size): individual = [random.randint(0, 1) for j in range(gene_size)] population.append(individual) return population # 选择操作 def selection(population): # 轮盘赌选择 fitness_values = [fitness(individual) for individual in population] total_fitness = sum(fitness_values) probabilities = [fitness/total_fitness for fitness in fitness_values] selected_population = [] for i in range(len(population)): selected_individual = None while selected_individual is None: for j in range(len(population)): if random.random() < probabilities[j]: selected_individual = population[j] break selected_population.append(selected_individual) return selected_population # 交叉操作 def crossover(parent1, parent2, crossover_rate): # 一点交叉 if random.random() > crossover_rate: return parent1, parent2 crossover_point = random.randint(1, len(parent1)-1) child1 = parent1[:crossover_point] + parent2[crossover_point:] child2 = parent2[:crossover_point] + parent1[crossover_point:] return child1, child2 # 变异操作 def mutation(individual, mutation_rate): # 每个基因以 mutation_rate 的概率发生变异 for i in range(len(individual)): if random.random() < mutation_rate: individual[i] = 1 - individual[i] return individual # 遗传算法 def genetic_algorithm(pop_size, gene_size, max_generation, crossover_rate, mutation_rate): population = init_population(pop_size, gene_size) for i in range(max_generation): population = selection(population) new_population = [] while len(new_population) < pop_size: parent1, parent2 = random.sample(population, 2) child1, child2 = crossover(parent1, parent2, crossover_rate) child1 = mutation(child1, mutation_rate) child2 = mutation(child2, mutation_rate) new_population.append(child1) new_population.append(child2) population = new_population best_individual = min(population, key=lambda individual: fitness(individual)) return best_individual # 测试 best_individual = genetic_algorithm(pop_size=100, gene_size=10, max_generation=1000, crossover_rate=0.8, mutation_rate=0.1) print(best_individual, fitness(best_individual)) ``` 在上面的代码中,定义了适应度函数、初始化种群、选择、交叉、变异等操作,并通过遗传算法不断迭代,最终得到最优解。在测试中,我们设定种群大小为100,染色体长度为10,最大迭代次数为1000,交叉率为0.8,变异率为0.1,得到的最优解为[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],适应度函数的值为0。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值