小编koh*_*ske的帖子

将超类实例转换为子类实例

  • 我有一个我无法触摸的外部库.该库有一个函数genA(),它返回类A的实例.
  • 在我这边,我将B类定义为A类的子类.
  • 我想在我的项目中使用B类的实例,但实例应该由genA()生成.

有没有标准和简单的方法来做到这一点?


# I cannnot tweak these code

def genA():
    a = A
    return(a)

class A:
    def __init__():
        self.a = 1

# ---

# code in my side

class B(A):
    def __init__():
        self.b = 2


a = genA()
# like a copy-constructor, doesn't work
# b = B(a)

# I want to get this
b.a # => 1
b.b # => 2
Run Code Online (Sandbox Code Playgroud)

这是一个等效的c ++代码:

#include <iostream>

// library side code
class A {
public:
  int a;
  // ... …
Run Code Online (Sandbox Code Playgroud)

python inheritance class function python-2.7

7
推荐指数
2
解决办法
2085
查看次数

用R5生成器对象显示类方法的定义

是否有任何官方方法在R5中使用R5生成器对象显示类方法的定义?

> cls <- setRefClass("cls", methods = list(f1 = function() {1}))
> 
> # of course we can get the definition via the instance
> a1 <- new("cls")
> a1$f1
Class method definition for method f1()
function () 
{
    1
}
<environment: 0x101d5d3f0>
> 
> # but how to get the difinition via the generator object, i.e., cls?
> cls$f1
Error in envRefInferField(x, what, getClass(class(x)), selfEnv) : 
  ‘f1’ is not a valid field or method name for reference class “refGeneratorSlot” …
Run Code Online (Sandbox Code Playgroud)

r

6
推荐指数
1
解决办法
455
查看次数

在R5引用类中定义类方法和类变量

我想知道在R5引用类中定义类方法和类变量的正确方法.

这是一个例子:

> # define R5 class XX
> # member variable: ma
> # member method: mfa
> XX <- setRefClass("XX",
+   fields = list(ma = "character"),
+   methods = list(
+     mfa = function() return(paste(ma, "*"))
+     ))
> 
> XX
Generator object for class "XX":

Class fields:

Name:         ma
Class: character

 Class Methods:  
    "callSuper", "copy", "export", "field", "getClass", "getRefClass", "import", "initFields", 
"mfa"


 Reference Superclasses:  
    "envRefClass"

> # create an instance of XX
> x <- XX$new(ma="ma")
> …
Run Code Online (Sandbox Code Playgroud)

oop r reference-class

5
推荐指数
1
解决办法
1036
查看次数

标签 统计

r ×2

class ×1

function ×1

inheritance ×1

oop ×1

python ×1

python-2.7 ×1

reference-class ×1