在 python 中,实例方法self
指向类实例,就像this
在 C# 中一样。在python中,类方法self
指向类。是否有 C# 等价物?
这可能很有用,例如:
Python 示例:
class A:
values = [1,2]
@classmethod
def Foo(self):
print "Foo called in class: ", self, self.values
@staticmethod
def Bar():
print "Same for all classes - there is no self"
class B(A):
# other code specific to class B
values = [1,2,3]
pass
class C(A):
# other code specific to class C
values = [1,2,3,4,5]
pass
A.Foo()
A.Bar()
B.Foo()
B.Bar()
C.Foo()
C.Bar()
结果是:
Foo called in class: __main__.A [1, 2]
Same for all classes - there is no self
Foo called in class: __main__.B [1, 2, 3]
Same for all classes - there is no self
Foo called in class: __main__.C [1, 2, 3, 4, 5]
Same for all classes - there is no self
这可能是一个很好的工具,因此类上下文中的通用代码(没有实例)可以提供由子类定义的自定义行为(不需要子类的实例)。
在我看来,C# 静态方法与 python 的静态方法完全一样,因为无法访问实际使用哪个类来调用该方法。
但是有没有办法在 C# 中执行类方法?或者至少确定哪个类调用了一个方法,例如:
public class A
{
public static List<int> values;
public static Foo()
{
Console.WriteLine("How can I figure out which class called this method?");
}
}
public class B : A
{
}
public class C : A
{
}
public class Program
{
public static void Main()
{
A.Foo();
B.Foo();
C.Foo();
}
}