Is there a way to do what classmethod
does in Python in C#?
That is, a static function that would get a Type object as an (implicit) parameter according to whichever subclass it's used from.
An example of what I want, approximately, is
class Base:
@classmethod
def get(cls, id):
print "Would instantiate a new %r with ID %d."%(cls, id)
class Puppy(Base):
pass
class Kitten(Base):
pass
p = Puppy.get(1)
k = Kitten.get(1)
the expected output being
Would instantiate a new <class __main__.Puppy at 0x403533ec> with ID 1.
Would instantiate a new <class __main__.Kitten at 0x4035341c> with ID 1.
(same code on codepad here.)
cls accepts the class Person as a parameter rather than Person's object/instance. Now, we pass the method Person. printAge as an argument to the function classmethod . This converts the method to a class method so that it accepts the first parameter as a class (i.e. Person).
@staticmethod function is nothing more than a function defined inside a class. It is callable without instantiating the class first. It's definition is immutable via inheritance. @classmethod function also callable without instantiating the class, but its definition follows Sub class, not Parent class, via inheritance.
You can use class methods for any methods that are not bound to a specific instance but the class. In practice, you often use class methods for methods that create an instance of the class. When a method creates an instance of the class and returns it, the method is called a factory method.
I think you want to take a look at generics.
Guide from MSFT:
http://msdn.microsoft.com/en-us/library/ms379564(VS.80).aspx
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With