How to overload __init__ method based on argument type?

2025-02-24 09:30:00
admin
原创
21
摘要:问题描述:Let's say I have a class that has a member called data which is a list. I want to be able to initialize the class with, for example, a filename (which...

问题描述:

Let's say I have a class that has a member called data which is a list.

I want to be able to initialize the class with, for example, a filename (which contains data to initialize the list) or with an actual list.

What's your technique for doing this?

Do you just check the type by looking at __class__?

Is there some trick I might be missing?

I'm used to C++ where overloading by argument type is easy.


解决方案 1:

A much neater way to get 'alternate constructors' is to use classmethods. For instance:

>>> 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
', 'bar
', 'baz
']
>>> MyData.fromdict({"spam": "ham"}).data
[('spam', 'ham')]

The reason it's neater is that there is no doubt about what type is expected, and you aren't forced to guess at what the caller intended for you to do with the datatype it gave you. The problem with isinstance(x, basestring) is that there is no way for the caller to tell you, for instance, that even though the type is not a basestring, you should treat it as a string (and not another sequence.) And perhaps the caller would like to use the same type for different purposes, sometimes as a single item, and sometimes as a sequence of items. Being explicit takes all doubt away and leads to more robust and clearer code.

解决方案 2:

with python3, you can use Implementing Multiple Dispatch with Function Annotations as Python Cookbook wrote:

import time


class Date(metaclass=MultipleMeta):
    def __init__(self, year:int, month:int, day:int):
        self.year = year
        self.month = month
        self.day = day

    def __init__(self):
        t = time.localtime()
        self.__init__(t.tm_year, t.tm_mon, t.tm_mday)

and it works like:

>>> d = Date(2012, 12, 21)
>>> d.year
2012
>>> e = Date()
>>> e.year
2018

解决方案 3:

Excellent question. I've tackled this problem as well, and while I agree that "factories" (class-method constructors) are a good method, I would like to suggest another, which I've also found very useful:

Here's a sample (this is a read method and not a constructor, but the idea is the same):

def read(self, str=None, filename=None, addr=0):
    """ Read binary data and return a store object. The data
        store is also saved in the interal 'data' attribute.

        The data can either be taken from a string (str 
        argument) or a file (provide a filename, which will 
        be read in binary mode). If both are provided, the str 
        will be used. If neither is provided, an ArgumentError 
        is raised.
    """
    if str is None:
        if filename is None:
            raise ArgumentError('Please supply a string or a filename')

        file = open(filename, 'rb')
        str = file.read()
        file.close()
    ...
    ... # rest of code

The key idea is here is using Python's excellent support for named arguments to implement this. Now, if I want to read the data from a file, I say:

obj.read(filename="blob.txt")

And to read it from a string, I say:

obj.read(str="x34x55")

This way the user has just a single method to call. Handling it inside, as you saw, is not overly complex

解决方案 4:

Quick and dirty fix

class MyData:
    def __init__(string=None,list=None):
        if string is not None:
            #do stuff
        elif list is not None:
            #do other stuff
        else:
            #make data empty

Then you can call it with

MyData(astring)
MyData(None, alist)
MyData()

解决方案 5:

A better way would be to use isinstance and type conversion. If I'm understanding you right, you want this:

def __init__ (self, filename):
    if isinstance (filename, basestring):
        # filename is a string
    else:
        # try to convert to a list
        self.path = list (filename)

解决方案 6:

You should use isinstance

isinstance(...)
    isinstance(object, class-or-type-or-tuple) -> bool

    Return whether an object is an instance of a class or of a subclass thereof.
    With a type as second argument, return whether that is the object's type.
    The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for
    isinstance(x, A) or isinstance(x, B) or ... (etc.).

解决方案 7:

You probably want the isinstance builtin function:

self.data = data if isinstance(data, list) else self.parse(data)

解决方案 8:

OK, great. I just tossed together this example with a tuple, not a filename, but that's easy. Thanks all.

class MyData:
    def __init__(self, data):
        self.myList = []
        if isinstance(data, tuple):
            for i in data:
                self.myList.append(i)
        else:
            self.myList = data

    def GetData(self):
        print self.myList

a = [1,2]

b = (2,3)

c = MyData(a)

d = MyData(b)

c.GetData()

d.GetData()

[1, 2]

[2, 3]

解决方案 9:

My preferred solution is:

class MyClass:
    _data = []
    __init__(self,data=None):
        # do init stuff
        if not data: return
        self._data = list(data) # list() copies the list, instead of pointing to it.

Then invoke it with either MyClass() or MyClass([1,2,3]).

Hope that helps. Happy Coding!

解决方案 10:

Why don't you go even more pythonic?

class AutoList:
def __init__(self, inp):
    try:                        ## Assume an opened-file...
        self.data = inp.read()
    except AttributeError:
        try:                    ## Assume an existent filename...
            with open(inp, 'r') as fd:
                self.data = fd.read()
        except:
            self.data = inp     ## Who cares what that might be?
相关推荐
  为什么项目管理通常仍然耗时且低效?您是否还在反复更新电子表格、淹没在便利贴中并参加每周更新会议?这确实是耗费时间和精力。借助软件工具的帮助,您可以一目了然地全面了解您的项目。如今,国内外有足够多优秀的项目管理软件可以帮助您掌控每个项目。什么是项目管理软件?项目管理软件是广泛行业用于项目规划、资源分配和调度的软件。它使项...
项目管理软件   1300  
  华为IPD产品开发流程是一套先进且成熟的产品开发管理体系,对众多企业提升产品竞争力有着重要的借鉴意义。它涵盖多个关键要素,这些要素相互关联、相互作用,共同构建起高效、科学的产品开发流程。深入剖析其中的五个核心要素,能让我们更好地理解华为成功背后的产品开发逻辑,为企业的产品创新与发展提供有力的指导。市场管理市场管理是IP...
IPD框架   20  
  华为集成产品开发(IPD)体系作为一套先进的产品开发管理理念和方法,在华为的发展历程中发挥了至关重要的作用。在供应链管理领域,IPD同样展现出巨大的价值,深刻影响着企业的运营效率、产品质量以及市场竞争力。通过将IPD理念融入供应链管理,华为实现了从产品规划到交付的全流程优化,为企业的持续发展奠定了坚实基础。IPD对供应...
IPD集成产品开发流程   23  
  IPD(Integrated Product Development)项目管理作为一种先进的产品开发管理模式,旨在通过整合跨部门资源,实现产品的高效开发与上市。然而,在实际推行过程中,IPD项目管理面临着诸多风险,若处理不当,可能导致项目进度延迟、成本超支甚至项目失败。深入了解这些风险并制定有效的应对策略,对于保障IP...
华为IPD流程   19  
  华为作为全球知名的科技企业,其成功背后的管理模式备受关注。其中,IPD(集成产品开发)产品开发流程对华为的创新发展起到了至关重要的推动作用。IPD不仅仅是一种流程,更是一种先进的管理理念,它将产品开发视为一个系统工程,涵盖了从市场需求分析、产品规划、研发、生产到上市等多个环节,通过整合企业内外部资源,实现高效、协同的产...
IPD流程中PDCP是什么意思   19  
热门文章
项目管理软件有哪些?
云禅道AD
禅道项目管理软件

云端的项目管理软件

尊享禅道项目软件收费版功能

无需维护,随时随地协同办公

内置subversion和git源码管理

每天备份,随时转为私有部署

免费试用