gpt4 book ai didi

python - 更改实例变量时更改另一个实例变量

转载 作者:太空宇宙 更新时间:2023-11-04 08:51:14 25 4
gpt4 key购买 nike

每次我们对类进行变量更改时,我希望能够更改类中的变量(在本例中为 greet)。

截图是这个:

class Greet(object):                                                                                        
def __init__(self, name="", age="", job=""):
self.name = name
self.age = age
self.job = job
self.greet = "Hello"

if self.name:
self.greet = self.greet + " " + self.name

if self.age:
self.greet = self.greet + ". Good to know that you is " + self.age + " years old"

if self.job:
self.greet = self.greet + ". I think being a " + self.job + " is amazing."

def shout(self):
print self.greet
return True

g1 = Greet(name="John Doe", job="Programmer")

g2 = Greet(name="Janis Duh", age="34", job="Singer")
g2.name = "Janis Joplin"

g3 = Greet()
g3.name = "Smith"
g3.age = "22"
g3.job = "Designer"

print ("Name %s\nAge %s\nJob %s\nGreet %s\n" % ( g1.name, g1.age, g1.job, g1.greet))
g1.shout

print ("Name %s\nAge %s\nJob %s\nGreet %s\n" % ( g2.name, g2.age, g2.job, g2.greet))
g2.shout

print ("Name %s\nAge %s\nJob %s\nGreet %s\n" % ( g3.name, g3.age, g3.job, g3.greet))
g3.shout

输出是:

Name John Doe
Age
Job Programmer
Greet Hello John Doe. I think being a Programmer is amazing.

Name Janis Joplin
Age 34
Job Singer
Greet Hello Janis Duh. Good to know that you is 34 years old. I think being a Singer is amazing.

Name Smith
Age 22 Job Designer
Greet Hello

shout 方法在任何情况下都不会正确打印“问候语”。即使在正确设置 self.greet 的情况下。

g1 对象打印正常,因为我在创建实例时声明了变量。

g2 正确更改了变量名,但问候语仍然指向旧值,似乎没有更新。

g3 更糟糕的是,可能出于同样的原因,g2 没有在问候时正确更新名称。

欢迎指点

(后期编辑)

按照 Adam Smith 的说法,我宁愿尝试将“greeting”保留为实例属性,如下所示:

def greet(self):
self.greeting = "Hello!"
if self.name:
self.greeting += " {0.name}."
if self.age:
self.greeting += " Good to know you are {0.age} years old."
if self.job:
self.greeting += " I think being a {0.job} is amazing."
print(self.greeting.format(self))

...

g = Greeter(...)
g.greet()

有效,但是

print g.greeting

给我这样的东西:

Hello! {0.name}. Good ...

最佳答案

听起来您需要在函数中生成它,因此每次调用它时都会计算它。

class Greeter(object):
def init(self, ...):
...

def greet(self):
greeting = "Hello!"
if self.name:
greeting += " {0.name}."
if self.age:
greeting += " Good to know you are {0.age} years old."
if self.job:
greeting += " I think being a {0.job} is amazing."
print(greeting.format(self))

关于python - 更改实例变量时更改另一个实例变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35023812/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com