Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
86 views
in Technique[技术] by (71.8m points)

How to make any method act as __init__ in Python?

When I run something like:

class Compliment():
   def __init__(self):
      self.Hello = "HI"
   def Bye(self):
      self.bye = "BYE"
print(Compliment().Hello)
print(Compliment().bye)

I get:`

AttributeError: 'Compliment' object has no attribute 'bye'
HI

But I want to create attributes in others methods, and make the method "init" useless for this purpose, Is this possible? If it is, how could I do something like that?

question from:https://stackoverflow.com/questions/65894267/how-to-make-any-method-act-as-init-in-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can create attributes anywhere you wish. The error with your code is that you did not invoke method Bye before you tried to print an attribute that is created only within that method. Instead, try

prop = Compliment()
print(prop.Hello)
prop.Bye()
print(prop.bye)

In answer to your direct question: no, you cannot make __init__ useless for creating attributes. You do not have to use it that way, but you cannot disable it: __init__ is a language-defined method.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...