Related
When I try to print an instance of a class, I get an output like this:
>>> class Test():
... def __init__(self):
... self.a = 'foo'
...
>>> print(Test())
<__main__.Test object at 0x7fc9a9e36d60>
How can I make it so that the print will show something custom (e.g. something that includes the a attribute value)? That is, how can I can define how the instances of the class will appear when printed (their string representation)?
See How can I choose a custom string representation for a class itself (not instances of the class)? if you want to define the behaviour for the class itself (in this case, so that print(Test) shows something custom, rather than <class __main__.Test> or similar). (In fact, the technique is essentially the same, but trickier to apply.)
>>> class Test:
... def __repr__(self):
... return "Test()"
... def __str__(self):
... return "member of Test"
...
>>> t = Test()
>>> t
Test()
>>> print(t)
member of Test
The __str__ method is what gets called happens when you print it, and the __repr__ method is what happens when you use the repr() function (or when you look at it with the interactive prompt).
If no __str__ method is given, Python will print the result of __repr__ instead. If you define __str__ but not __repr__, Python will use what you see above as the __repr__, but still use __str__ for printing.
As Chris Lutz explains, this is defined by the __repr__ method in your class.
From the documentation of repr():
For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval(), otherwise the representation is a string enclosed in angle brackets that contains the name of the type of the object together with additional information often including the name and address of the object. A class can control what this function returns for its instances by defining a __repr__() method.
Given the following class Test:
class Test:
def __init__(self, a, b):
self.a = a
self.b = b
def __repr__(self):
return f"<Test a:{self.a} b:{self.b}>"
def __str__(self):
return f"From str method of Test: a is {self.a}, b is {self.b}"
..it will act the following way in the Python shell:
>>> t = Test(123, 456)
>>> t
<Test a:123 b:456>
>>> print(repr(t))
<Test a:123 b:456>
>>> print(t)
From str method of Test: a is 123, b is 456
>>> print(str(t))
From str method of Test: a is 123, b is 456
If no __str__ method is defined, print(t) (or print(str(t))) will use the result of __repr__ instead
If no __repr__ method is defined then the default is used, which is roughly equivalent to:
def __repr__(self):
cls = self.__class__
return f"<{cls.__module_}.{cls.__qualname__} object at {id(self)}>"
If you're in a situation like #Keith you could try:
print(a.__dict__)
It goes against what I would consider good style but if you're just trying to debug then it should do what you want.
A generic way that can be applied to any class without specific formatting could be done as follows:
class Element:
def __init__(self, name, symbol, number):
self.name = name
self.symbol = symbol
self.number = number
def __str__(self):
return str(self.__class__) + ": " + str(self.__dict__)
And then,
elem = Element('my_name', 'some_symbol', 3)
print(elem)
produces
__main__.Element: {'symbol': 'some_symbol', 'name': 'my_name', 'number': 3}
A prettier version of response by #user394430
class Element:
def __init__(self, name, symbol, number):
self.name = name
self.symbol = symbol
self.number = number
def __str__(self):
return str(self.__class__) + '\n'+ '\n'.join(('{} = {}'.format(item, self.__dict__[item]) for item in self.__dict__))
elem = Element('my_name', 'some_symbol', 3)
print(elem)
Produces visually nice list of the names and values.
<class '__main__.Element'>
name = my_name
symbol = some_symbol
number = 3
An even fancier version (thanks Ruud) sorts the items:
def __str__(self):
return str(self.__class__) + '\n' + '\n'.join((str(item) + ' = ' + str(self.__dict__[item]) for item in sorted(self.__dict__)))
Simple. In the print, do:
print(foobar.__dict__)
as long as the constructor is
__init__
For Python 3:
If the specific format isn't important (e.g. for debugging) just inherit from the Printable class below. No need to write code for every object.
Inspired by this answer
class Printable:
def __repr__(self):
from pprint import pformat
return "<" + type(self).__name__ + "> " + pformat(vars(self), indent=4, width=1)
# Example Usage
class MyClass(Printable):
pass
my_obj = MyClass()
my_obj.msg = "Hello"
my_obj.number = "46"
print(my_obj)
Just to add my two cents to #dbr's answer, following is an example of how to implement this sentence from the official documentation he's cited:
"[...] to return a string that would yield an object with the same value when passed to eval(), [...]"
Given this class definition:
class Test(object):
def __init__(self, a, b):
self._a = a
self._b = b
def __str__(self):
return "An instance of class Test with state: a=%s b=%s" % (self._a, self._b)
def __repr__(self):
return 'Test("%s","%s")' % (self._a, self._b)
Now, is easy to serialize instance of Test class:
x = Test('hello', 'world')
print 'Human readable: ', str(x)
print 'Object representation: ', repr(x)
print
y = eval(repr(x))
print 'Human readable: ', str(y)
print 'Object representation: ', repr(y)
print
So, running last piece of code, we'll get:
Human readable: An instance of class Test with state: a=hello b=world
Object representation: Test("hello","world")
Human readable: An instance of class Test with state: a=hello b=world
Object representation: Test("hello","world")
But, as I said in my last comment: more info is just here!
You need to use __repr__. This is a standard function like __init__.
For example:
class Foobar():
"""This will create Foobar type object."""
def __init__(self):
print "Foobar object is created."
def __repr__(self):
return "Type what do you want to see here."
a = Foobar()
print a
__repr__ and __str__ are already mentioned in many answers. I just want to add that if you are too lazy to add these magic functions to your class, you can use objprint. A simple decorator #add_objprint will help you add the __str__ method to your class and you can use print for the instance. Of course if you like, you can also use objprint function from the library to print any arbitrary objects in human readable format.
from objprint import add_objprint
class Position:
def __init__(self, x, y):
self.x = x
self.y = y
#add_objprint
class Player:
def __init__(self):
self.name = "Alice"
self.age = 18
self.items = ["axe", "armor"]
self.coins = {"gold": 1, "silver": 33, "bronze": 57}
self.position = Position(3, 5)
print(Player())
The output is like
<Player
.name = 'Alice',
.age = 18,
.items = ['axe', 'armor'],
.coins = {'gold': 1, 'silver': 33, 'bronze': 57},
.position = <Position
.x = 3,
.y = 5
>
>
There are already a lot of answers in this thread but none of them particularly helped me, I had to work it out myself, so I hope this one is a little more informative.
You just have to make sure you have parentheses at the end of your class, e.g:
print(class())
Here's an example of code from a project I was working on:
class Element:
def __init__(self, name, symbol, number):
self.name = name
self.symbol = symbol
self.number = number
def __str__(self):
return "{}: {}\nAtomic Number: {}\n".format(self.name, self.symbol, self.number
class Hydrogen(Element):
def __init__(self):
super().__init__(name = "Hydrogen", symbol = "H", number = "1")
To print my Hydrogen class, I used the following:
print(Hydrogen())
Please note, this will not work without the parentheses at the end of Hydrogen. They are necessary.
Hope this helps, let me know if you have anymore questions.
Even though this is an older post, there is also a very convenient method introduced in dataclasses (as of Python 3.7). Besides other special functions such as __eq__ and __hash__, it provides a __repr__ function for class attributes. You example would then be:
from dataclasses import dataclass, field
#dataclass
class Test:
a: str = field(default="foo")
b: str = field(default="bar")
t = Test()
print(t)
# prints Test(a='foo', b='bar')
If you want to hide a certain attribute from being outputted, you can set the field decorator parameter repr to False:
#dataclass
class Test:
a: str = field(default="foo")
b: str = field(default="bar", repr=False)
t = Test()
print(t)
# prints Test(a='foo')
When I try to print an instance of a class, I get an output like this:
>>> class Test():
... def __init__(self):
... self.a = 'foo'
...
>>> print(Test())
<__main__.Test object at 0x7fc9a9e36d60>
How can I make it so that the print will show something custom (e.g. something that includes the a attribute value)? That is, how can I can define how the instances of the class will appear when printed (their string representation)?
See How can I choose a custom string representation for a class itself (not instances of the class)? if you want to define the behaviour for the class itself (in this case, so that print(Test) shows something custom, rather than <class __main__.Test> or similar). (In fact, the technique is essentially the same, but trickier to apply.)
>>> class Test:
... def __repr__(self):
... return "Test()"
... def __str__(self):
... return "member of Test"
...
>>> t = Test()
>>> t
Test()
>>> print(t)
member of Test
The __str__ method is what gets called happens when you print it, and the __repr__ method is what happens when you use the repr() function (or when you look at it with the interactive prompt).
If no __str__ method is given, Python will print the result of __repr__ instead. If you define __str__ but not __repr__, Python will use what you see above as the __repr__, but still use __str__ for printing.
As Chris Lutz explains, this is defined by the __repr__ method in your class.
From the documentation of repr():
For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval(), otherwise the representation is a string enclosed in angle brackets that contains the name of the type of the object together with additional information often including the name and address of the object. A class can control what this function returns for its instances by defining a __repr__() method.
Given the following class Test:
class Test:
def __init__(self, a, b):
self.a = a
self.b = b
def __repr__(self):
return f"<Test a:{self.a} b:{self.b}>"
def __str__(self):
return f"From str method of Test: a is {self.a}, b is {self.b}"
..it will act the following way in the Python shell:
>>> t = Test(123, 456)
>>> t
<Test a:123 b:456>
>>> print(repr(t))
<Test a:123 b:456>
>>> print(t)
From str method of Test: a is 123, b is 456
>>> print(str(t))
From str method of Test: a is 123, b is 456
If no __str__ method is defined, print(t) (or print(str(t))) will use the result of __repr__ instead
If no __repr__ method is defined then the default is used, which is roughly equivalent to:
def __repr__(self):
cls = self.__class__
return f"<{cls.__module_}.{cls.__qualname__} object at {id(self)}>"
If you're in a situation like #Keith you could try:
print(a.__dict__)
It goes against what I would consider good style but if you're just trying to debug then it should do what you want.
A generic way that can be applied to any class without specific formatting could be done as follows:
class Element:
def __init__(self, name, symbol, number):
self.name = name
self.symbol = symbol
self.number = number
def __str__(self):
return str(self.__class__) + ": " + str(self.__dict__)
And then,
elem = Element('my_name', 'some_symbol', 3)
print(elem)
produces
__main__.Element: {'symbol': 'some_symbol', 'name': 'my_name', 'number': 3}
A prettier version of response by #user394430
class Element:
def __init__(self, name, symbol, number):
self.name = name
self.symbol = symbol
self.number = number
def __str__(self):
return str(self.__class__) + '\n'+ '\n'.join(('{} = {}'.format(item, self.__dict__[item]) for item in self.__dict__))
elem = Element('my_name', 'some_symbol', 3)
print(elem)
Produces visually nice list of the names and values.
<class '__main__.Element'>
name = my_name
symbol = some_symbol
number = 3
An even fancier version (thanks Ruud) sorts the items:
def __str__(self):
return str(self.__class__) + '\n' + '\n'.join((str(item) + ' = ' + str(self.__dict__[item]) for item in sorted(self.__dict__)))
Simple. In the print, do:
print(foobar.__dict__)
as long as the constructor is
__init__
For Python 3:
If the specific format isn't important (e.g. for debugging) just inherit from the Printable class below. No need to write code for every object.
Inspired by this answer
class Printable:
def __repr__(self):
from pprint import pformat
return "<" + type(self).__name__ + "> " + pformat(vars(self), indent=4, width=1)
# Example Usage
class MyClass(Printable):
pass
my_obj = MyClass()
my_obj.msg = "Hello"
my_obj.number = "46"
print(my_obj)
Just to add my two cents to #dbr's answer, following is an example of how to implement this sentence from the official documentation he's cited:
"[...] to return a string that would yield an object with the same value when passed to eval(), [...]"
Given this class definition:
class Test(object):
def __init__(self, a, b):
self._a = a
self._b = b
def __str__(self):
return "An instance of class Test with state: a=%s b=%s" % (self._a, self._b)
def __repr__(self):
return 'Test("%s","%s")' % (self._a, self._b)
Now, is easy to serialize instance of Test class:
x = Test('hello', 'world')
print 'Human readable: ', str(x)
print 'Object representation: ', repr(x)
print
y = eval(repr(x))
print 'Human readable: ', str(y)
print 'Object representation: ', repr(y)
print
So, running last piece of code, we'll get:
Human readable: An instance of class Test with state: a=hello b=world
Object representation: Test("hello","world")
Human readable: An instance of class Test with state: a=hello b=world
Object representation: Test("hello","world")
But, as I said in my last comment: more info is just here!
You need to use __repr__. This is a standard function like __init__.
For example:
class Foobar():
"""This will create Foobar type object."""
def __init__(self):
print "Foobar object is created."
def __repr__(self):
return "Type what do you want to see here."
a = Foobar()
print a
__repr__ and __str__ are already mentioned in many answers. I just want to add that if you are too lazy to add these magic functions to your class, you can use objprint. A simple decorator #add_objprint will help you add the __str__ method to your class and you can use print for the instance. Of course if you like, you can also use objprint function from the library to print any arbitrary objects in human readable format.
from objprint import add_objprint
class Position:
def __init__(self, x, y):
self.x = x
self.y = y
#add_objprint
class Player:
def __init__(self):
self.name = "Alice"
self.age = 18
self.items = ["axe", "armor"]
self.coins = {"gold": 1, "silver": 33, "bronze": 57}
self.position = Position(3, 5)
print(Player())
The output is like
<Player
.name = 'Alice',
.age = 18,
.items = ['axe', 'armor'],
.coins = {'gold': 1, 'silver': 33, 'bronze': 57},
.position = <Position
.x = 3,
.y = 5
>
>
There are already a lot of answers in this thread but none of them particularly helped me, I had to work it out myself, so I hope this one is a little more informative.
You just have to make sure you have parentheses at the end of your class, e.g:
print(class())
Here's an example of code from a project I was working on:
class Element:
def __init__(self, name, symbol, number):
self.name = name
self.symbol = symbol
self.number = number
def __str__(self):
return "{}: {}\nAtomic Number: {}\n".format(self.name, self.symbol, self.number
class Hydrogen(Element):
def __init__(self):
super().__init__(name = "Hydrogen", symbol = "H", number = "1")
To print my Hydrogen class, I used the following:
print(Hydrogen())
Please note, this will not work without the parentheses at the end of Hydrogen. They are necessary.
Hope this helps, let me know if you have anymore questions.
Even though this is an older post, there is also a very convenient method introduced in dataclasses (as of Python 3.7). Besides other special functions such as __eq__ and __hash__, it provides a __repr__ function for class attributes. You example would then be:
from dataclasses import dataclass, field
#dataclass
class Test:
a: str = field(default="foo")
b: str = field(default="bar")
t = Test()
print(t)
# prints Test(a='foo', b='bar')
If you want to hide a certain attribute from being outputted, you can set the field decorator parameter repr to False:
#dataclass
class Test:
a: str = field(default="foo")
b: str = field(default="bar", repr=False)
t = Test()
print(t)
# prints Test(a='foo')
When I try to print an instance of a class, I get an output like this:
>>> class Test():
... def __init__(self):
... self.a = 'foo'
...
>>> print(Test())
<__main__.Test object at 0x7fc9a9e36d60>
How can I make it so that the print will show something custom (e.g. something that includes the a attribute value)? That is, how can I can define how the instances of the class will appear when printed (their string representation)?
See How can I choose a custom string representation for a class itself (not instances of the class)? if you want to define the behaviour for the class itself (in this case, so that print(Test) shows something custom, rather than <class __main__.Test> or similar). (In fact, the technique is essentially the same, but trickier to apply.)
>>> class Test:
... def __repr__(self):
... return "Test()"
... def __str__(self):
... return "member of Test"
...
>>> t = Test()
>>> t
Test()
>>> print(t)
member of Test
The __str__ method is what gets called happens when you print it, and the __repr__ method is what happens when you use the repr() function (or when you look at it with the interactive prompt).
If no __str__ method is given, Python will print the result of __repr__ instead. If you define __str__ but not __repr__, Python will use what you see above as the __repr__, but still use __str__ for printing.
As Chris Lutz explains, this is defined by the __repr__ method in your class.
From the documentation of repr():
For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval(), otherwise the representation is a string enclosed in angle brackets that contains the name of the type of the object together with additional information often including the name and address of the object. A class can control what this function returns for its instances by defining a __repr__() method.
Given the following class Test:
class Test:
def __init__(self, a, b):
self.a = a
self.b = b
def __repr__(self):
return f"<Test a:{self.a} b:{self.b}>"
def __str__(self):
return f"From str method of Test: a is {self.a}, b is {self.b}"
..it will act the following way in the Python shell:
>>> t = Test(123, 456)
>>> t
<Test a:123 b:456>
>>> print(repr(t))
<Test a:123 b:456>
>>> print(t)
From str method of Test: a is 123, b is 456
>>> print(str(t))
From str method of Test: a is 123, b is 456
If no __str__ method is defined, print(t) (or print(str(t))) will use the result of __repr__ instead
If no __repr__ method is defined then the default is used, which is roughly equivalent to:
def __repr__(self):
cls = self.__class__
return f"<{cls.__module_}.{cls.__qualname__} object at {id(self)}>"
If you're in a situation like #Keith you could try:
print(a.__dict__)
It goes against what I would consider good style but if you're just trying to debug then it should do what you want.
A generic way that can be applied to any class without specific formatting could be done as follows:
class Element:
def __init__(self, name, symbol, number):
self.name = name
self.symbol = symbol
self.number = number
def __str__(self):
return str(self.__class__) + ": " + str(self.__dict__)
And then,
elem = Element('my_name', 'some_symbol', 3)
print(elem)
produces
__main__.Element: {'symbol': 'some_symbol', 'name': 'my_name', 'number': 3}
A prettier version of response by #user394430
class Element:
def __init__(self, name, symbol, number):
self.name = name
self.symbol = symbol
self.number = number
def __str__(self):
return str(self.__class__) + '\n'+ '\n'.join(('{} = {}'.format(item, self.__dict__[item]) for item in self.__dict__))
elem = Element('my_name', 'some_symbol', 3)
print(elem)
Produces visually nice list of the names and values.
<class '__main__.Element'>
name = my_name
symbol = some_symbol
number = 3
An even fancier version (thanks Ruud) sorts the items:
def __str__(self):
return str(self.__class__) + '\n' + '\n'.join((str(item) + ' = ' + str(self.__dict__[item]) for item in sorted(self.__dict__)))
Simple. In the print, do:
print(foobar.__dict__)
as long as the constructor is
__init__
For Python 3:
If the specific format isn't important (e.g. for debugging) just inherit from the Printable class below. No need to write code for every object.
Inspired by this answer
class Printable:
def __repr__(self):
from pprint import pformat
return "<" + type(self).__name__ + "> " + pformat(vars(self), indent=4, width=1)
# Example Usage
class MyClass(Printable):
pass
my_obj = MyClass()
my_obj.msg = "Hello"
my_obj.number = "46"
print(my_obj)
Just to add my two cents to #dbr's answer, following is an example of how to implement this sentence from the official documentation he's cited:
"[...] to return a string that would yield an object with the same value when passed to eval(), [...]"
Given this class definition:
class Test(object):
def __init__(self, a, b):
self._a = a
self._b = b
def __str__(self):
return "An instance of class Test with state: a=%s b=%s" % (self._a, self._b)
def __repr__(self):
return 'Test("%s","%s")' % (self._a, self._b)
Now, is easy to serialize instance of Test class:
x = Test('hello', 'world')
print 'Human readable: ', str(x)
print 'Object representation: ', repr(x)
print
y = eval(repr(x))
print 'Human readable: ', str(y)
print 'Object representation: ', repr(y)
print
So, running last piece of code, we'll get:
Human readable: An instance of class Test with state: a=hello b=world
Object representation: Test("hello","world")
Human readable: An instance of class Test with state: a=hello b=world
Object representation: Test("hello","world")
But, as I said in my last comment: more info is just here!
You need to use __repr__. This is a standard function like __init__.
For example:
class Foobar():
"""This will create Foobar type object."""
def __init__(self):
print "Foobar object is created."
def __repr__(self):
return "Type what do you want to see here."
a = Foobar()
print a
__repr__ and __str__ are already mentioned in many answers. I just want to add that if you are too lazy to add these magic functions to your class, you can use objprint. A simple decorator #add_objprint will help you add the __str__ method to your class and you can use print for the instance. Of course if you like, you can also use objprint function from the library to print any arbitrary objects in human readable format.
from objprint import add_objprint
class Position:
def __init__(self, x, y):
self.x = x
self.y = y
#add_objprint
class Player:
def __init__(self):
self.name = "Alice"
self.age = 18
self.items = ["axe", "armor"]
self.coins = {"gold": 1, "silver": 33, "bronze": 57}
self.position = Position(3, 5)
print(Player())
The output is like
<Player
.name = 'Alice',
.age = 18,
.items = ['axe', 'armor'],
.coins = {'gold': 1, 'silver': 33, 'bronze': 57},
.position = <Position
.x = 3,
.y = 5
>
>
There are already a lot of answers in this thread but none of them particularly helped me, I had to work it out myself, so I hope this one is a little more informative.
You just have to make sure you have parentheses at the end of your class, e.g:
print(class())
Here's an example of code from a project I was working on:
class Element:
def __init__(self, name, symbol, number):
self.name = name
self.symbol = symbol
self.number = number
def __str__(self):
return "{}: {}\nAtomic Number: {}\n".format(self.name, self.symbol, self.number
class Hydrogen(Element):
def __init__(self):
super().__init__(name = "Hydrogen", symbol = "H", number = "1")
To print my Hydrogen class, I used the following:
print(Hydrogen())
Please note, this will not work without the parentheses at the end of Hydrogen. They are necessary.
Hope this helps, let me know if you have anymore questions.
Even though this is an older post, there is also a very convenient method introduced in dataclasses (as of Python 3.7). Besides other special functions such as __eq__ and __hash__, it provides a __repr__ function for class attributes. You example would then be:
from dataclasses import dataclass, field
#dataclass
class Test:
a: str = field(default="foo")
b: str = field(default="bar")
t = Test()
print(t)
# prints Test(a='foo', b='bar')
If you want to hide a certain attribute from being outputted, you can set the field decorator parameter repr to False:
#dataclass
class Test:
a: str = field(default="foo")
b: str = field(default="bar", repr=False)
t = Test()
print(t)
# prints Test(a='foo')
I'm trying to filter tweets by hashtag and output the text of the Tweet.
The class Tweet contains the overarching tweet info, of which I only need "text". I know that str method needs to be used to call each instance of the class, but down below when I "print", the above class is inaccessible. Please help :D
Edit: what's the implication of replacing __str__ with __repr__ in class Tweet? Thanks!
class Tweet():
tweet = Tweet()
def __init__(self, tweet_dict = {}):
if "statuses" in tweet_dict:
self.status = tweet_dict["statuses"]
else:
self.status = ""
if "text" in self.status:
self.text = item["text"]
else:
self.text = ""
def __str__(self):
tweet_info = self.text
return tweet_info
#-------------------------------------------------------------------
tweet_inst = []
for dic in statuses:
item_instances = Tweet(dic)
tweet_inst.append(item_instances)
print(tweet_inst)
First of all, the second line, tweet = Tweet() in the class definition is wrong. You cannot create a class variable containing an instance of said class.
Second, you assign self.text = item["text"] in line 11. What is item? Should that rather be tweet_dict?
Third, you could directly return self.text in __str__, no need to assign it to a varibale tweet_info first.
Last, but not least, you should not use mutable datatypes as default arguments, like you do in line 4. Here's why.
__str__ needs to return a string representation of the object.
__str__ goal is to be readable, __repr__ goal is to be unambiguous.
When you print a list (which is tweet_inst), it iterates over the objects (of Tweet) contained in the list and call their __repr__.
You want to add def __repr__(self): return str(self) so they do the same thing, then it will return self.text instead of the object default representation (which is it's location in memory)
class Tweet(object):
def __init__(self, x):
self.x = x
def __str__(self):
return self.x
def __repr__(self):
return '__repr__' + str(self.x)
>>> t1 = Tweet('t1')
>>> t2 = Tweet('t2')
>>> list_ = [t1, t2]
>>> print(list_)
[__repr__t1, __repr__t2]
Rather than the default
[<__main__.Tweet object at 0x02AFA810>, <__main__.Tweet object at 0x029E2BF0>]
Here is a great answer by moshez about the difference between the two.
OK, in C# we have something like:
public static string Destroy(this string s) {
return "";
}
So basically, when you have a string you can do:
str = "This is my string to be destroyed";
newstr = str.Destroy()
# instead of
newstr = Destroy(str)
Now this is cool because in my opinion it's more readable. Does Python have something similar? I mean instead of writing like this:
x = SomeClass()
div = x.getMyDiv()
span = x.FirstChild(x.FirstChild(div)) # so instead of this
I'd like to write:
span = div.FirstChild().FirstChild() # which is more readable to me
Any suggestion?
You can just modify the class directly, sometimes known as monkey patching.
def MyMethod(self):
return self + self
MyClass.MyMethod = MyMethod
del(MyMethod)#clean up namespace
I'm not 100% sure you can do this on a special class like str, but it's fine for your user-defined classes.
Update
You confirm in a comment my suspicion that this is not possible for a builtin like str. In which case I believe there is no analogue to C# extension methods for such classes.
Finally, the convenience of these methods, in both C# and Python, comes with an associated risk. Using these techniques can make code more complex to understand and maintain.
You can do what you have asked like the following:
def extension_method(self):
#do stuff
class.extension_method = extension_method
I would use the Adapter pattern here. So, let's say we have a Person class and in one specific place we would like to add some health-related methods.
from dataclasses import dataclass
#dataclass
class Person:
name: str
height: float # in meters
mass: float # in kg
class PersonMedicalAdapter:
person: Person
def __init__(self, person: Person):
self.person = person
def __getattr__(self, item):
return getattr(self.person, item)
def get_body_mass_index(self) -> float:
return self.person.mass / self.person.height ** 2
if __name__ == '__main__':
person = Person('John', height=1.7, mass=76)
person_adapter = PersonMedicalAdapter(person)
print(person_adapter.name) # Call to Person object field
print(person_adapter.get_body_mass_index()) # Call to wrapper object method
I consider it to be an easy-to-read, yet flexible and pythonic solution.
You can change the built-in classes by monkey-patching with the help of forbidden fruit
But installing forbidden fruit requires a C compiler and unrestricted environment so it probably will not work or needs hard effort to run on Google App Engine, Heroku, etc.
I changed the behaviour of unicode class in Python 2.7 for a Turkish i,I uppercase/lowercase problem by this library.
# -*- coding: utf8 -*-
# Redesigned by #guneysus
import __builtin__
from forbiddenfruit import curse
lcase_table = tuple(u'abcçdefgğhıijklmnoöprsştuüvyz')
ucase_table = tuple(u'ABCÇDEFGĞHIİJKLMNOÖPRSŞTUÜVYZ')
def upper(data):
data = data.replace('i',u'İ')
data = data.replace(u'ı',u'I')
result = ''
for char in data:
try:
char_index = lcase_table.index(char)
ucase_char = ucase_table[char_index]
except:
ucase_char = char
result += ucase_char
return result
curse(__builtin__.unicode, 'upper', upper)
class unicode_tr(unicode):
"""For Backward compatibility"""
def __init__(self, arg):
super(unicode_tr, self).__init__(*args, **kwargs)
if __name__ == '__main__':
print u'istanbul'.upper()
You can achieve this nicely with the following context manager that adds the method to the class or object inside the context block and removes it afterwards:
class extension_method:
def __init__(self, obj, method):
method_name = method.__name__
setattr(obj, method_name, method)
self.obj = obj
self.method_name = method_name
def __enter__(self):
return self.obj
def __exit__(self, type, value, traceback):
# remove this if you want to keep the extension method after context exit
delattr(self.obj, self.method_name)
Usage is as follows:
class C:
pass
def get_class_name(self):
return self.__class__.__name__
with extension_method(C, get_class_name):
assert hasattr(C, 'get_class_name') # the method is added to C
c = C()
print(c.get_class_name()) # prints 'C'
assert not hasattr(C, 'get_class_name') # the method is gone from C
I'd like to think that extension methods in C# are pretty much the same as normal method call where you pass the instance then arguments and stuff.
instance.method(*args, **kwargs)
method(instance, *args, **kwargs) # pretty much the same as above, I don't see much benefit of it getting implemented in python.
After a week, I have a solution that is closest to what I was seeking for. The solution consists of using getattr and __getattr__. Here is an example for those who are interested.
class myClass:
def __init__(self): pass
def __getattr__(self, attr):
try:
methodToCall = getattr(myClass, attr)
return methodToCall(myClass(), self)
except:
pass
def firstChild(self, node):
# bla bla bla
def lastChild(self, node):
# bla bla bla
x = myClass()
div = x.getMYDiv()
y = div.firstChild.lastChild
I haven't test this example, I just gave it to give an idea for who might be interested. Hope that helps.
C# implemented extension methods because it lacks first class functions, Python has them and it is the preferred method for "wrapping" common functionality across disparate classes in Python.
There are good reasons to believe Python will never have extension methods, simply look at the available built-ins:
len(o) calls o.__len__
iter(o) calls o.__iter__
next(o) calls o.next
format(o, s) calls o.__format__(s)
Basically, Python likes functions.