Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (16.4k points)
Suppose I have a class that has a part called information which is a list.

I need to have the option to instate the class with, for instance, a filename (which contains information to introduce the list) or with an actual list.

What's your procedure for doing this?

Do you simply check the sort by looking at __class__?

Is there some trick which I may be missing?

I'm utilized to C++ where overloading by contention type is simple.

1 Answer

0 votes
by (26.4k points)

Try the following code:

>>> class MyData:

...     def __init__(self, data):

...         "Initialize MyData from a sequence"

...         self.data = data

...     

...     @classmethod

...     def fromfilename(cls, filename):

...         "Initialize MyData from a file"

...         data = open(filename).readlines()

...         return cls(data)

...     

...     @classmethod

...     def fromdict(cls, datadict):

...         "Initialize MyData from a dict's items"

...         return cls(datadict.items())

... 

>>> MyData([1, 2, 3]).data

[1, 2, 3]

>>> MyData.fromfilename("/tmp/foobar").data

['foo\n', 'bar\n', 'baz\n']

>>> MyData.fromdict({"spam": "ham"}).data

[('spam', 'ham')]

Are you interested to learn the concepts of Python? Join the python training course fast!

To know more about this you can have a look at the following video tutorial:-

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Apr 3, 2021 in Java by dante07 (13.1k points)

Browse Categories

...