Reputation:
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?
Upvotes: 0
Views: 74
Reputation: 159
class Compliment():
def __init__(self):
self.Hello = "HI"
@property
def bye(self):
return "BYE"
> print(Compliment().Hello)
HI
> print(Compliment().bye)
BYE
python class property decorator is executed at initialization.
It can be automatically generated and used without having to run a separate function.
Upvotes: 0
Reputation: 77900
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.
Upvotes: 1