I need to accept emails via SMTP, for this decided to use SMTPD Lib in Python. There is a class SMTPChannel - is it possible to add a method to this class? I rather need not extend it, but do something that my method would be there on load...
Asked
Active
Viewed 415 times
0
MB-F
- 21,224
- 4
- 58
- 107
user1692333
- 2,271
- 5
- 31
- 63
-
2For a pretty extensive discussion of this and related topics (e.g. adding a method to an object instance), see this SO post: http://stackoverflow.com/questions/972/adding-a-method-to-an-existing-object – zehnpaard Jan 08 '15 at 08:32
1 Answers
4
You can dynamically add members to anything at runtime, including methods. You just need to define the method as a function separately, and then augment the type with the method:
def someMethod (self):
# do something with self
SMTPChannel.someMethod = someMethod
Afterwards, all objects of type SMTPChannel will have access to that method.
Note that doing this will not work with the name mangling Python does for members starting with two underscores. So you can’t really do anything, you can’t do with the SMTPChannel object from “outside”.
poke
- 339,995
- 66
- 523
- 574
-
When do this python says `
:SMTPChannel instance has no attribute '__greeting'`. This attr actually exists in the class. – user1692333 Jan 08 '15 at 10:52 -
-
so if I understand correctly there is no pretty way to add a new method in this case in my situation? The only way - just take a module source and rewrite it for my purpose? – user1692333 Jan 08 '15 at 11:02
-
You *can* access the attribute as `_SMTPChannel__greeting`, but you probably shouldn’t if you can avoid it. – poke Jan 08 '15 at 11:04
-
This line comes from the original source https://hg.python.org/cpython/file/2.7/Lib/smtpd.py#l196 so i need to use it and also few more. I just want to do it in right way just extending the module rather that creating a new one from sources. – user1692333 Jan 08 '15 at 11:08