您不应该引用变量的名称(这是可能的,但这是一个黑暗魔法:D)
必须将名称作为参数传递给类:class Monster:
def __init__ (self, name, age):
self.name = name
self.age = age
def greet (self):
print ("Hello, I'm", self.name, "of age", self.age, ".")
person = Monster("Monster",340)
person.greet() #prints Hello, I'm Monster of age 340 .
您可以稍后更改:
^{pr2}$
或者,如果需要,可以使用以下方法进行更改:class Monster:
def __init__ (self, name, age):
self.name = name
self.age = age
def greet (self):
print("Hello, I'm", self.name, "of age", self.age, ".")
def rename (self, new_name):
self.name = new_name
def new_age (self, new_age):
self.age = new_age
person = Monster("Bob", 35)
person.greet() # prints Hello, I'm Bob of age 35 .
person.rename("John")
person.new_age(36)
person.greet() # prints Hello, I'm John of age 36 .