I'm quite new to Python OOP and trying to create a class I can generate instances of in these two ways according to whether I want to customize the instance or not:
alien_one = Alien(1)
alien_two = Alien(1).customize(anger=5, emotion=1)
I got the following code working after messing around with classmethods and staticmethods, which I feel I should have been using according to other threads:
class Alien(object):
def __init__(self, polarity):
self.polarity = {1 : 'friendly', 2 : 'aggressive'}
def customize(self, **kwargs):
for event in kwargs:
# // process events to change self.polarity
return self
Is this code appropriate for creating an instance of Alien or should I be using method decorators to generate the instance? There is just something that feels broken about this before I've started.
Edit: Thanks all for the responses, the general consensus is to pass any expressions or kwargs into __init__
. Some of the example code I have been referring to looked like this:
query = Tweet.update(is_published=True).where(Tweet.creation_date < today)
which is an example taken from the Peewee ORM. When I have tried to use method decorators (static/class) inside my class I have lost the is_published
parameter and have no access to it. For understanding more clearly can anybody explain how both is_published
and Tweet.creation_date
is likely to be received inside the class object, it does seem that query is a brand new instance of the Tweet class. I'm only using Peewee as an example to understand how this code works rather than trying to figure how any details of Peewee works itself.
Presumably you're doing this to mutate your instances after creation. If this is the case, consider restructuring your code for immutability as there are very real advantages in many situations. If you're not mutating, take @katy lavallee's advice and move this into __init__.
You can use the setattr built to programmatically set fields on an instance:
for key, val in kwargs.items():
setattr(self, key, val)
If this is python 2 (if so, make the switch) you'll want to replace the call to items() with iteritems().