【问题标题】:does python has a way to implement C#-like indexers? [duplicate]python有没有办法实现类似C#的索引器? [复制]
【发布时间】:2016-05-05 17:21:28
【问题描述】:

如何在python c# indexers-like this[int i] {get set}中实现?也就是说,如何在python中编写以下代码?

public class foo{
    ...
    List<foo2> objfoo;
    ...
    public foo2 this[int i] {
      get{ return objfoo[i]; }}
}//end class foo

//in another class or method...
ofoo = new foo();
...
foo2 X = ofoo[3];

【问题讨论】:

标签: c# python


【解决方案1】:

如果你想让一个类的工作类似于Python list(类似于其他语言中的数组),你可以继承列表并为你的类提供自定义方法和属性,而无需覆盖任何列表方法或属性除非你需要。

试图模仿您发布的一些内容:

class foo(list):
    def __init__(self, *args):
        self.extend(args)
        self.x = "Now"

    def smack(self):
        print("Smackity!")

ofoo = foo(1, 2, 3, 4, 5, 6)
print(ofoo[3])  # Prints 4
print(ofoo.x)   # Prints "Now"
ofoo.smack()    # Prints "Smackity!"

您可以使用普通列表方法以任何您想要的方式添加或更改索引项。

另外,这里是more on lists,如果有帮助的话。

【讨论】:

    猜你喜欢
    • 2014-11-08
    • 1970-01-01
    • 2011-10-12
    • 2014-11-24
    • 1970-01-01
    • 2010-10-09
    • 1970-01-01
    • 2011-03-12
    相关资源
    最近更新 更多