function – Pythonic way of creating a class in python 2.7.6
a=A() where A is a class is the pythonic way,
__init__ is already a function.
If you extend a class but do not call the base-classes
__init__s you just get their functions, for example.
By the way, you can pass stuff to constructors.
class A(object): def __init__(self,extra): print(Look, extra: ,extra)
I dismissed the OP as a tard/noob who didnt really know what a constructor did, sorry for that, heres a better answer:
this is an object orientated thing, a function could do but you want that to belong somehow to your class, you could put them in the same python package, or a static method. If I had a complex number class, Id make conjugate a static method because it belongs with complex numbers, however Id put something that used complex numbers, but what not important to all complex numbers outside.
Suppose I had a
__str__ function, obviously goes inside because every complex number can do this. Suppose I have a input two numbers function that prints out the complex number the user inputs, that is a function that happens to use complex numbers, therefore not a static method, or method.
Heres my example:
#! /usr/bin/python class reading_thing_maybe(object): def __init__(self,filename=None): #usual constructor code print tConstructor! if not filename is None: print tSpecial case, constructing but doing readfile right away! self.readfile(filename) def readfile(self,filename): print tReding file:,filename class other_reading_thing(object): def __init__(self): print tConstructor def readfile(self,filename): print tReding file:,filename @staticmethod def read_from_file(filename): print tconstructing with a read from,filename result = other_reading_thing() result.readfile(filename) return result if __name__ == __main__: print normal a = reading_thing_maybe() print assuming constructor takes nothing b = reading_thing_maybe(hello) print using the filename= format c = reading_thing_maybe(filename=use me if constructor takes arguments) print Static method d = other_reading_thing.read_from_file(test)
[email protected] ~ $ chmod +x ./example.py [email protected] ~ $ ./example.py normal Constructor! assuming constructor takes nothing Constructor! Special case, constructing but doing readfile right away! Reding file: hello using the filename= format Constructor! Special case, constructing but doing readfile right away! Reding file: use me if constructor takes arguments Static method constructing with a read from test Constructor Reding file: test [email protected] ~ $