小编use*_*113的帖子

Python替换函数[替换一次]

我需要帮助我用Python编写的程序.

假设我想每一个字的情况下更换"steak""ghost"(只是用它去......),但我也希望每一个字的情况下更换"ghost""steak"在同一时间.以下代码不起作用:

 s="The scary ghost ordered an expensive steak"
 print s
 s=s.replace("steak","ghost")
 s=s.replace("ghost","steak")
 print s
Run Code Online (Sandbox Code Playgroud)

它打印: The scary steak ordered an expensive steak

我想要得到的是 The scary steak ordered an expensive ghost

python string replace

22
推荐指数
3
解决办法
3079
查看次数

Python改变类变量

好的,这次我会非常清楚.

class Yes:

    def __init__(self):
        self.a=1

    def yes(self):
        if self.a==1:
            print "Yes"
        else:
            print "No, but yes"

class No(Yes):

    def no(self):
        if self.a==1:
            print "No"
        else:
            print "Yes, but no"
        self.a-=1 #Note this line
Run Code Online (Sandbox Code Playgroud)

现在,在运行时:

Yes().yes()
No().no()
Yes().yes()
No().no()
Run Code Online (Sandbox Code Playgroud)

我希望它打印出来:

Yes
No
No, but yes
Yes, but no
Run Code Online (Sandbox Code Playgroud)

它给了我:

Yes
No
Yes
No
Run Code Online (Sandbox Code Playgroud)

现在,我知道原因是因为我只改变了No类中Self.a的值(还记得那行吗?).我想知道是否还有在Yes类中更改它仍然在No类中(就好像我可以插入一些代替self.a- = 1的东西).

python variables class

5
推荐指数
1
解决办法
3万
查看次数

标签 统计

python ×2

class ×1

replace ×1

string ×1

variables ×1