标签: object-composition

如何使python类支持项目分配?

在查看Think Complexity中的一些代码时,我注意到他们的Graph类为自己分配值.我已经从该类中复制了一些重要的行,并编写了一个示例类,ObjectChild但这种行为失败了.

class Graph(dict):
    def __init__(self, vs=[], es=[]):
        for v in vs:
            self.add_vertex(v)

        for e in es:
            self.add_edge(e)

    def add_edge(self, e):
        v, w = e
        self[v][w] = e
        self[w][v] = e

    def add_vertex(self, v):
        self[v] = {}

class ObjectChild(object):
    def __init__(self, name):
        self['name'] = name
Run Code Online (Sandbox Code Playgroud)

我确定不同的内置类型都有自己的使用方式,但我不确定这是否应该尝试构建到我的类中.有可能,怎么样?这是我不应该打扰的东西,而是依靠简单的构图,例如self.l = [1, 2, 3]?在内置类型之外应该避免吗?

我问,因为我被告知"你几乎不应该继承内置的python集合"; 建议我犹豫是否要限制自己.

为了澄清,我知道它ObjectChild不会"起作用",我可以很容易地使它 "工作",但我很好奇这些内置类型的内部工作方式使它们的界面与一个孩子不同object.

python inheritance built-in-types object-composition

15
推荐指数
4
解决办法
1万
查看次数

唯一指针和const正确性

我没想到要编译这段代码:

#include <iostream>
#include <memory>

class A
{
public:

    inline int get() const
    {
        return m_i;
    }

    inline void set(const int & i)
    {
        m_i = i;
    }

private:

    int m_i;
};

int main()
{
    const auto ptr = std::make_unique< A >();

    ptr->set( 666 ); // I do not like this line    D:<
    std::cout << ptr->get( ) << std::endl;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

如果ptr是一个原始C指针,我会好的.但由于我使用的是智能指针,我无法理解这背后的基本原理是什么.

我使用唯一指针来表达所有权,在面向对象编程中,这可以被视为对象组合("部分关系").

例如:

class Car
{
    /** Engine built through some creational …
Run Code Online (Sandbox Code Playgroud)

c++ pointers smart-pointers const-correctness object-composition

7
推荐指数
1
解决办法
5940
查看次数

在ASP.NET MVC3项目中编写多态对象

我的问题的本质是如何用MVC3和Ninject以合理的方式组合这些对象(见下文)(尽管我不确定DI应该在解决方案中发挥作用).我无法透露我的项目的真实细节,但这是一个近似,说明了问题/问题.在VB或C#中的答案表示赞赏!

我有几种不同的产品,具有各种各样的特性,但它们都需要在目录中表示.每个产品类在我的数据库中都有一个对应的表.商品具有一些特定于商品的属性,因此拥有自己的表.我已经为目录条目定义了一个接口,其目的是调用DescriptionText属性将根据底层的具体类型给出非常不同的结果.

Public Class Clothing
    Property Identity as Int64
    Property AvailableSizes As List(Of String)
    Property AvailableColor As List(Of String)
End Class

Public Class Fasteners
    Property Identity as Int64
    Property AvailableSizes As List(Of String)
    Property AvailableFinishes As List(Of String)
    Property IsMetric As Boolean
End Class

Public Interface ICatalogEntry
    Property ProductId as Int64
    Property PublishedOn As DateTime
    Property DescriptionText As String
End Interface
Run Code Online (Sandbox Code Playgroud)

鉴于DescriptionText是表示层关注的问题,我不想在我的产品类中实现ICatalogEntry接口.相反,我想将其委托给某种格式化程序.

Public Interface ICatalogEntryFormatter
    Property DescriptionText As String
End Interface

Public Class ClothingCatalogEntryFormatter
    Implements ICatalogEntryFormatter

    Property DescriptionText As String …
Run Code Online (Sandbox Code Playgroud)

asp.net-mvc dependency-injection object-composition ninject-extensions

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

用于DI的NEventStore组件的对象组成

我正在将NEventStore添加到我现有的项目中,而我正在使用DI.

我想要一个CommonDomain.Persistence.EventStore.IRepository注入我的MVC控制器的实例.这个接口的唯一实现EventStoreRepository.
这个类依赖于IConstructAggregates我发现唯一实现AggregateFactory被标记为内部的,位于测试项目,具有非常古怪的文件名.

我不应该使用IRepository?(为什么它被标记为公共而不被任何内部代码消耗?)
我在这里查看示例项目并IRepository用于操作聚合.

或者我应该自己实施IConstructAggregates

c# dependency-injection object-composition event-sourcing neventstore

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

pandas:链接方法的组合,如.resample(),.rolling()等

我想构建一个扩展pandas.DataFrame- 让我们称之为SPDF- 它可以做到超出简单的DataFrame能力:

import pandas as pd
import numpy as np


def to_spdf(func):
    """Transform generic output of `func` to SPDF.

    Returns
    -------
    wrapper : callable
    """
    def wrapper(*args, **kwargs):
        res = func(*args, **kwargs)
        return SPDF(res)

    return wrapper


class SPDF:
    """Special-purpose dataframe.

    Parameters
    ----------
    df : pandas.DataFrame

    """

    def __init__(self, df):
        self.df = df

    def __repr__(self):
        return repr(self.df)

    def __getattr__(self, item):
        res = getattr(self.df, item)

        if callable(res):
            res = to_spdf(res)

        return res


if __name__ == …
Run Code Online (Sandbox Code Playgroud)

python chained object-composition pandas

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

对象组合促进代码重用.(T/F,为什么)

我正在读考试,我正试图解决这个问题.具体问题是"继承和对象组合都促进了代码重用.(T/F)",但我相信我理解了问题的继承部分.

我相信继承促进了代码重用,因为类似的方法可以放在抽象基类中,这样类似的方法就不必在多个子类中相同地实现.例如,如果你有三种形状,并且每个形状的方法"getName"只返回一个数据成员'_name',那么为什么在每个子类中重新实现这个方法时,它可以在抽象基础中实现一次阶级"形状".

但是,我对对象组合的最好理解是对象/类之间的"有一个"关系.例如,学生有学校,学校有很多学生.这可以看作是对象组成,因为它们之间没有真正存在(没有任何学生的学校不完全是学校,是吗?等等).但我认为这两个对象作为数据成员彼此"拥有"的方式无法促进代码重用.

有帮助吗?谢谢!

c++ oop object-composition

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

替代PImpl成语 - 优势与劣势?

传统的PImpl Idiom是这样的:

#include <memory>

struct Blah
{
    //public interface declarations

private:
    struct Impl;
    std::unique_ptr<Impl> impl;
};

//in source implementation file:

struct Blah::Impl
{
    //private data
};
//public interface definitions
Run Code Online (Sandbox Code Playgroud)

但是,为了好玩,我尝试使用具有私有继承的组合:

[Test.h]

#include <type_traits>
#include <memory>

template<typename Derived>
struct PImplMagic
{
    PImplMagic()
    {
        static_assert(std::is_base_of<PImplMagic, Derived>::value,
                      "Template parameter must be deriving class");
    }
//protected: //has to be public, unfortunately
    struct Impl;
};

struct Test : private PImplMagic<Test>,
              private std::unique_ptr<PImplMagic<Test>::Impl>
{
    Test();
    ~Test();
    void f();
};
Run Code Online (Sandbox Code Playgroud)

[第一个翻译单位]

#include "Test.h"
int main() …
Run Code Online (Sandbox Code Playgroud)

c++ pimpl-idiom composition object-composition c++11

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

使用 __getattr__ 方法作为组合模式是良好的 Python 实践吗?

首先 - 如果这是重复的,请接受我的道歉 - 我有一种感觉,我以前见过某种类似的讨论,但我真的找不到它。

我的问题是关于 Python 中的对象组合,它应该看起来像是从复合类的每个次要类中继承的。用例是多个对象实例共享属性及其值的公共核心(而不仅仅是公共结构,这将是经典的继承情况)。

我可以使用一个简单的属性来做到这一点,即只需让每个类都有一个名为“shared_attributes”的属性,该属性本身就是一个存储所有值的类:

class CoreClass(object):
    def __init__(self):
        self.attr = 'asdf'


class CompClass1(object):
    def __init__(self, core):
        self.core_attr = core


class CompClass2(object):
    def __init__(self, core):
        self.core_attr = core
Run Code Online (Sandbox Code Playgroud)

但这要求我通过属性访问每个共享属性class.core_attr,这是我不想要的(出于多种原因,其中之一是这需要对大段代码进行大量重写)。

因此,我想使用依赖于 Python 内置__getattr__对象方法的复合模式,如下所示:

class TestClass1(object):
    def __init__(self):
        self.attr1 = 1

    def func_a(self):
        return 'a'


class CompClassBase(object):
    def __init__(self, test_class):
        self.comp_obj = test_class

    def __getattr__(self, item):
        return getattr(self.comp_obj, item)


class CompClass1(CompClassBase):
    def __init__(self, test_class):
        CompClassBase.__init__(self, test_class)
        self.attr2 = 13

    def func_b(self):
        return '1b'


class …
Run Code Online (Sandbox Code Playgroud)

python object-composition

5
推荐指数
0
解决办法
1259
查看次数

可变参数模板函子调用

因此,我一直在尝试使用可变参数模板从更方便的子类型中组合对象,但是我很难使它完全按照我的要求进行操作。

template<class ...Functor>
struct SeqMethod:public Functor...{
  template<class F>
  void call(F& a){
    F::operator()();
  }
  template<class F,class ... funcs>
  void call(){
    F::operator()();

    call<funcs...>();
  }
  public:
  void operator()(){
    call<Functor...>();
  }
};
Run Code Online (Sandbox Code Playgroud)

这是无效的语法,因此就可以了。

理想情况下,我希望能够使用这样的东西

class A{
public:
  void operator()(){
    std::cout<<"A";
  }
};
class B{
public:
  void operator()(){
    std::cout<<"B";
  }
};

class C:public SeqMethod<A,B>{};
Run Code Online (Sandbox Code Playgroud)

在这种情况下,应输出“ AB”,并且通常适合将行为组合在一起。

c++ object-composition variadic-templates

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

Java - 为什么ClassName.this.variable在变量是静态时工作?

我试图完全理解"这个"是如何工作的.在我之前的帖子中,我理解为什么我们使用"this"关键字.

我对static的理解是该类有该成员的一个副本."this"用于表示当前对象.对于所有对象,静态成员变量是相同的,那么为什么"this"对静态成员变量起作用?

码:

public class OuterInnerClassExample
{
    public static void main(String[] args)
    {
        OuterClass outClassObj = new OuterClass(10);
        outClassObj.setInt(11);
        outClassObj.setInt(12);

        System.out.println("Total Count: " + outClassObj.getCount() );
    }
}

class OuterClass
{
    private int test;
    private static int count;       // total sum of how many new objects are created & the times all of them have been changed

    public OuterClass(int test)
    {
        this.test = test;
//      count += 1;                 // preferred as count is static
        this.count += 1;            // …
Run Code Online (Sandbox Code Playgroud)

java static class this object-composition

4
推荐指数
1
解决办法
1374
查看次数