![]() ![]() It is very simple to use constructors when dealing with single classes. ![]() It's usually a better idea to just have the caller tell you explicitly what kind of object was meant, by using different keyword arguments. In Python, we create a constructor by defining the init method. For example: if you want to take either a filename or a file-like object you cannot use isinstance(arg, file), because there are many file-like objects that do not subclass file (like the ones returned from urllib, or StringIO, or.). First, the name of the constructor method is always init in Python. As this data structure is not code, you can use it in one direction to parse data into Pythonic objects, and in the other. Constructors typically look like methods, but they have a couple of special features. Instead of writing imperative code to parse a piece of data, you declaratively define a data structure that describes your data. Isinstance is best avoided because Python's duck typing makes it hard to figure out what kind of object was actually passed in. Construct is a powerful declarative and symmetrical parser and builder for binary data. Notice all those class methods still go through the same _init_, but using class methods can be much more convenient than having to remember what combinations of keyword arguments to _init_ work. This is just a silly example, but I hope you get the idea: class C(object): If using just keyword arguments becomes unwieldy, you can combine it with classmethods (the bzrlib code likes this approach). If you want to be able to pass in different kinds of argument, I would try to avoid the isinstance-based approach mentioned in another answer, and instead use keyword arguments. If your signatures differ only in the number of arguments, using default arguments is the right way to do it. ![]()
0 Comments
Leave a Reply. |
Details
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |