如何在类声明中使用`__str__`方法来打印格式化的字符串?

huangapple go评论75阅读模式
英文:

How do I use the __str__ method within a class declaration to print a formatted string?

问题

I checked the other similar question to this, but it's not asking nearly the same thing. My problem is that I'm trying to use a __str__ method inside of a Python 3's class definition to access some variables that have already been passed into the class via the constructor.

When the class prints, I want it to print a formatted string with two variables inserted. When I pass the variables into the __str__ declaration, I get one error. When I call the variables in the actual formatted string (with or without self-dot) I get two more errors.

The only way I know to make it work is to pass the specific variables into the __str__ method header as default values def __str__(self, name="john", age=23):

I know there's only one real way to do this. Am I supposed to use __repr__ with __str__ in order for it to work? Here's the source code:

class Tenderloin():

    def __main__(self, nameo="none", age=0, nation="none", race="none", personality="none"):
        self.nameo = nameo
        self.age = age
        self.nation = nation
        self.race = race
        self.personality = personality

    def __init__(self, nameo, age, nation, race, personality):
        print("Hi. My name is " + str(nameo) + ". I am " + str(age) + " years old.\nI come from " + str(nation) + " of the " + str(race) + " race. My personality is " + str(personality))

    def __str__(self, name, age):
        return f"This is  {str(self.nameo)},  {str(self.age)}."

john = Tenderloin("John Jenkins", 23, "America", "black", "nice")
jellaye = Tenderloin("Jellaye Flabbaghan", 48, "Hindustan", "Crustasian", "bellowing")
print(str(john))
print(str(jellaye))

gets = input("Please press Enter.")

(Note: I've removed the HTML encoding from your code.)

英文:

I checked the other similar question to this, but it's not asking nearly the same thing. My problem is that I'm trying to use a __str__ method inside of a Python 3's class definition to access some variables that have already been passed into the class via the constructor.

When the class prints, I want it to print a formatted string with two variables inserted. When I pass the variables into the __str__ declaration, I get one error. When I call the variables in the actual formatted string (with or without self-dot) I get two more errors.

The only way I know to make it work is to pass the specific variables into the __str__ method header as default values def __str__(self, name="john", age = 23):

I know there's only one real way to do this. Am I supposed to use __repr__ with __str__ in order for it to work? Here's the source code:

class Tenderloin( ):

	def __main__(self, nameo = "none", age= 0, nation = "none", race = "none", personality = "none"):
	
		self.nameo = nameo;
		self.age = age;
		self.nation = nation;
		self.race = race;
		self.personality = personality;

	def __init__(self, nameo, age, nation, race, personality):
		print("Hi. My name is " + str(nameo) + ". I am " + str(age) + " years old.\nI come from " + str(nation) + " of the " + str		(race) + " race. My personality is " + str(personality));
	
	def __str__(self, name, age):
		return  f"This is  {str(self.nameo)},  {str(self.age)}.";
		

john = Tenderloin("John Jenkins", 23, "America", "black", "nice"); 
jellaye = Tenderloin("Jellaye Flabbaghan", 48, "Hindustand", "Crustasian", "bellowing");
print(str(john));
print(str(jellaye));	

gets = input("Please press Enter.");

答案1

得分: 1

不存在名为__main__的实例方法(这种命名样式保留给内置方法),str 方法的签名是 def __str__(self),在 print 内部不需要显式调用 str()。唯一使用 __main__ 的方式如下:

    class Tenderloin:
    
        def __init__(self, nameo="none", age=0, nation="none", race="none", personality="none"):
            self.nameo = nameo
            self.age = age
            self.nation = nation
            self.race = race
            self.personality = personality
    
        def __str__(self):
            return f"This is {self.nameo}, {self.age}."
    
    
    if __name__ == '__main__':
        john = Tenderloin("John Jenkins", 23, "America", "black", "nice")
        jellaye = Tenderloin("Jellaye Flabbaghan", 48, "Hindustand", "Crustasian", "bellowing")
        print(john)
        print(jellaye)

Python 不需要在行末加;

英文:

There is no such thing as existing __main__ instance method (that name style is reserved for builtin methods), also the signature for the str method is def __str__(self) and you don't need to call explicit str() around inside a print.

The only use of __main__ that you'll have is like this

class Tenderloin:

    def __init__(self, nameo="none", age=0, nation="none", race="none", personality="none"):
        self.nameo = nameo
        self.age = age
        self.nation = nation
        self.race = race
        self.personality = personality

    def __str__(self):
        return f"This is {self.nameo}, {self.age}."


if __name__ == '__main__':
    john = Tenderloin("John Jenkins", 23, "America", "black", "nice")
    jellaye = Tenderloin("Jellaye Flabbaghan", 48, "Hindustand", "Crustasian", "bellowing")
    print(john)
    print(jellaye)

And python doesn't need ; at the end of lines

答案2

得分: 0

这应该现在可以工作。

class Tenderloin( ):

    def __init__(self, nameo="none", age=0, nation="none", race="none", personality="none"):
        self.nameo = nameo
        self.age = age
        self.nation = nation
        self.race = race
        self.personality = personality

        print("Hi. My name is " + str(nameo) + ". I am " + str(age) + " years old.\nI come from " + str(nation) + " of the " + str(race) + " race. My personality is " + str(personality))

    def __str__(self):
        return f"This is {str(self.nameo)}, {str(self.age)}."

john = Tenderloin("John Jenkins", 23, "America", "black", "nice")
jellaye = Tenderloin("Jellaye Flabbaghan", 48, "Hindustand", "Crustasian", "bellowing")
print(str(john))
print(str(jellaye))

gets = input("Please press Enter.")
英文:

This should work now.

class Tenderloin( ):

    def __init__(self, nameo = "none", age= 0, nation = "none", race = "none", personality = "none"):
        self.nameo = nameo
        self.age = age
        self.nation = nation
        self.race = race
        self.personality = personality

        print("Hi. My name is " + str(nameo) + ". I am " + str(age) + " years old.\nI come from " + str(nation) + " of the " + str      (race) + " race. My personality is " + str(personality))
    
    def __str__(self):
        return  f"This is  {str(self.nameo)},  {str(self.age)}."
        

john = Tenderloin("John Jenkins", 23, "America", "black", "nice"); 
jellaye = Tenderloin("Jellaye Flabbaghan", 48, "Hindustand", "Crustasian", "bellowing")
print(str(john))
print(str(jellaye))

gets = input("Please press Enter.")

答案3

得分: 0

抱歉,我不会回答你的翻译请求。

英文:

I'm sorry. I inadvertently answered my own question for a second time. I had a working version of the Python class with the str method in a jupyter notebook, but I didn't have an internet connection at the time so I couldn't review it. Basically, the str method that formats a string for printing the object is only meant to be used in jupyter notebooks (and maybe VBC, I'm not sure). It's not supposed to be used for someone who's just dinking around in a PY file in Notepad. Yes, I do most of my programming in Notepad.

huangapple
  • 本文由 发表于 2023年6月11日 23:29:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/76451180.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定