Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python-style classmethod for C#?

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.)

like image 828
AKX Avatar asked Jan 13 '10 17:01

AKX


People also ask

What is CLS () in Python?

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).

What is the difference between @staticmethod and @classmethod?

@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.

When should you use a Classmethod Python?

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.


1 Answers

I think you want to take a look at generics.

Guide from MSFT:

http://msdn.microsoft.com/en-us/library/ms379564(VS.80).aspx

like image 107
Hamish Grubijan Avatar answered Oct 02 '22 22:10

Hamish Grubijan