Reputation: 81721
In the code following, OP created a class with inheriting Template class class BatchRename(Template):
and at the bottom of the code, he is instantiating the class as t = BatchRename(fmt)
albeit there is no construction method (def __init__():
). As I understand inheritance in Python, there might be something wrong with this code but I am new to Python so I might be missing something. Could anyone explain me this?
Little code explaining: The OP shows how to use custom delimiters in Templates and he is doing a Batch Renaming on some files in the example. He is creating a custom class which inherits from Template to change the delimeter
name(field,property,attribute) and use the inner functionality at the same time.
>>> import time, os.path
>>> photofiles = ['img_1074.jpg', 'img_1076.jpg', 'img_1077.jpg']
>>> class BatchRename(Template):
... delimiter = '%'
>>> fmt = raw_input('Enter rename style (%d-date %n-seqnum %f-format): ')
Enter rename style (%d-date %n-seqnum %f-format): Ashley_%n%f
>>> t = BatchRename(fmt)
>>> date = time.strftime('%d%b%y')
>>> for i, filename in enumerate(photofiles):
... base, ext = os.path.splitext(filename)
... newname = t.substitute(d=date, n=i, f=ext)
... print '{0} --> {1}'.format(filename, newname)
img_1074.jpg --> Ashley_0.jpg
img_1076.jpg --> Ashley_1.jpg
img_1077.jpg --> Ashley_2.jpg
I took this code from: http://docs.python.org/tutorial/stdlib2.html#templating
Upvotes: 1
Views: 348
Reputation: 10119
The class BatchRename
doesn't need to have a __init__
at all because it's inheriting that from the super class Template
. Example:
class A:
def __init__(self):
self.age = 27
class B(A):
pass # Does nothing
>>> A().age
27
>>> B().age # Calling __init__ from super class A
27
Upvotes: 2
Reputation: 363587
You don't need an __init__
in every Python class; it's optional and only called when present. The actual constructor for new-style Python classes is __new__
, which is inherited from object
:
>>> class Foo(object):
... pass
...
>>> Foo()
<__main__.Foo object at 0x021757F0>
>>> Foo(1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: object.__new__() takes no parameters
If a class inherits from a class that does provide __init__
, that function is inherited along, just like any other method. This is different from, say, C++, where constructors are treated as being special and are not inherited.
Upvotes: 3