相关疑难解决方法(0)

在Python中重新分类实例

我有一个由外部库提供给我的课程.我已经创建了这个类的子类.我也有一个原始类的实例.

我现在想要将此实例转换为我的子类的实例,而不更改实例已有的任何属性(除了我的子类覆盖的那些属性).

以下解决方案似乎有效.

# This class comes from an external library. I don't (want) to control
# it, and I want to be open to changes that get made to the class
# by the library provider.
class Programmer(object):
    def __init__(self,name):
        self._name = name

    def greet(self):
        print "Hi, my name is %s." % self._name

    def hard_work(self):
        print "The garbage collector will take care of everything."

# This is my subclass.
class C_Programmer(Programmer):
    def __init__(self, *args, **kwargs):
        super(C_Programmer,self).__init__(*args, **kwargs)
        self.learn_C()

    def …
Run Code Online (Sandbox Code Playgroud)

python subclass

56
推荐指数
2
解决办法
9272
查看次数

这相当于Python中的复制构造函数吗?

我正在审查一些旧的python代码并经常遇到这个'模式':

class Foo(object):
    def __init__(self, other = None):
        if other:
            self.__dict__ = dict(other.__dict__)
Run Code Online (Sandbox Code Playgroud)

这是复制构造函数通常在Python中实现的方式吗?

python

5
推荐指数
2
解决办法
2234
查看次数

在python中复制构造函数

我想知道是否有可能像在java中一样在python中执行复制构造函数,这是我的java代码,常规承包商和复制构造函数.如何在python中编写以下代码?谢谢

public Date(int day, int month, int year)
{
    _day = day;
    _month = month;
    _year = year;

    if(!checkDate(_day,_month,_year))
    {
        _day = DEFAULT_DAY;
        _month = DEFAULT_DAY;
        _year = DEFAULT_YEAR;
    }        
}

/**
 * Copy constructor.
 */
public Date (Date other)
{
    if(other != null)
    {
      _day = other._day;
      _month = other._month;
      _year = other._year;
    }
}
Run Code Online (Sandbox Code Playgroud)

python

2
推荐指数
1
解决办法
719
查看次数

标签 统计

python ×3

subclass ×1