在运行代码时,是否有方法更新类中的“self”?

2024-04-25 17:04:48 发布

您现在位置:Python中文网/ 问答频道 /正文

Write a Python class (rotater) whose init function will take in a single additional argument which is a string; an internal variable (store) will be set to that string. There is also a function in this class called evolve which will take in a single additional argument n that specifies how many rotations should be applied to store. E.g., if store was "abed" and evolve(l) was called, then store would be updated to "bcda". If evolve(l) were the called, then store would be "cdab" (from "bcda"). If evolve(2) were then called, then store would be "abed" (from "cdab"). Evolve should both update store, and return the updated value of store.

我的代码运行得非常好,只是它不能更新类“rotater”中的“self”对象。问题要求更新store,并返回store的更新值

class rotater:
    def __init__(self,store):
        self.store=store
    def evolve(self,n):
        shift=self.store[:int(n)]
        new_string=self.store[int(n):]+shift
        store=new_string
        return store

我期望在两次调用函数evolve之后,字符串将进化两次。 但在第一次之后,情况仍然是一样的


Tags: tostoreinselfstringinitfunctionbe
1条回答
网友
1楼 · 发布于 2024-04-25 17:04:48
class rotater:
    def __init__(self,store):
        self.store=store
    def evolve(self,n):
        shift=self.store[:int(n)]
        new_string=self.store[int(n):]+shift
        self.store = new_string
        return new_string

这样就可以重新定义store属性(要定义属性,必须将其写入sintax self.attribute = value而不是attribute = value

相关问题 更多 >

    热门问题