Last active
December 12, 2015 02:58
-
-
Save stangirala/4702652 to your computer and use it in GitHub Desktop.
Example for immutable inheritance and an example for __new__().
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class IntWrapper(int): | |
| ''' int wrapper class. Example for use of __new__().''' | |
| _valmod5 = None | |
| def __new__(cls, value): | |
| ''' Do something to differentiate from int.''' | |
| self = int.__new__(cls, value) # create an immutable | |
| return self | |
| def valmod5(self): | |
| _valmod5 = self % 5 | |
| return _valmod5 | |
| def self_value(self): | |
| ''' Actual instance.''' | |
| return self | |
| if __name__ == '__main__': | |
| a = IntWrapper(256) | |
| print a.self_value(), a.valmod5() # 'print a' works the same as 'a.self_value()' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment