Python static method get class

Python static method to get class instance python

Solution 1: That is the very definition of a static method: it is called without a class argument (as in class methods) and without an instance argument (as in instance methods). Solution 3: As option, if you need determine class from staticmethod (not classmethod)

How to get the class name of a staticmethod

not possible with staticmethod . is possible, however, with classmethod

class A(object): @classmethod def f(cls): print cls 

By definition, a staticmethod is not provided with a reference to either an invoking class or instance — that’s what «static» means in Python.

You can do some hacky things to achieve this with either metaclasses or decorators.

Note that I’m using the example idea of just getting the class’s name from your post, however, you can modify this example to work with any kind of function you want to have as a static function. You would just define that function inside getnameable below, like I have defined getname and make use of the some_class argument below (and you’d use a different name than all the «getname» stuff I use here).

Читайте также:  Php сбросить кэш браузера

With decorators, you could do this:

def getnameable(some_class): # Note, this could be any kind of static method that you want, not # just for getting the name. And it can use `some_class` in whatever # way is needed. def getname(): return some_class.__name__ some_class.getname = staticmethod(getname) return some_class 
In [334]: @getnameable class SubClassA(BaseClass): pass . In [335]: SubClassA.getname() Out[335]: 'SubClassA' 

but note that if you implemented this in BaseClass directly, then the class name which gets bound would be BaseClass , even in the children classes. So in this case, you’d need to put the decorator on every class you wanted.

Metaclasses offers away around that, by indicating that you want this business of decorating the class to be part of class-creation (not instance creation, mind you).

class GetNameableMeta(type): def __new__(cls, name, bases, attrs): temp_class = super(GetNameableMeta, cls).__new__(cls, name, bases, attrs) return getnameable(temp_class) class BaseClass(object): __metaclass__ = GetNameableMeta class SubClassA(BaseClass): pass 
In [337]: %cpaste Pasting code; enter '--' alone on the line to stop or use Ctrl-D. :class GetNameableMeta(type): : def __new__(cls, name, bases, attrs): : temp_class = super(GetNameableMeta, cls).__new__(cls, name, bases, attrs) : return getnameable(temp_class) : :class BaseClass(object): : __metaclass__ = GetNameableMeta : :class SubClassA(BaseClass): : pass :-- In [338]: SubClassA.getname() Out[338]: 'SubClassA' In [339]: BaseClass.getname() Out[339]: 'BaseClass' 

Notice how much high-falutin code we needed to write to do this, when we had several reasonable alternatives:

  1. Just ask directly for the __name__ attribute.
  2. Make it a classmethod to begin with.
  3. Use the decorators just where we need this and give up the inheritance part.

I suspect that in «the essence of Python» any of these is better than the machinery I describe above, since it makes for simpler, easier to understand code.

How to get class name of a class static method through inspection, That is the very definition of a static method: it is called without a class argument (as in class methods) and without an instance argument

Instance Class and Static Methods Python Programming Tutorial

Learn about the three different types of methods within a class in this python tutorial. Duration: 8:05

25 — (OOP) Instance method, Class method & Static method in Python

Instance method is the most common method in python class and is also Static method does
Duration: 9:59

Class method vs. static method in Python

The difference between class and static methods in Python is small. Some people use the Duration: 5:19

How to get class name of a class static method through inspection

That is the very definition of a static method: it is called without a class argument (as in class methods) and without an instance argument (as in instance methods). The only real difference between a function declared in module scope and a static method is that the method name is defined in the class’ namespace and not in the module’s namespace.

In other words, you can’t get to the class object directly. You can get the function name by examining the stack (although I am not sure how useful it is):

>>> import sys >>> import traceback >>> class A(object): @staticmethod def a(): trace() >>> def trace(): print traceback.extract_stack(sys._getframe())[-3][3] >>> A.a() A.a() 

And given the name, you could get to the class object by extracting from the name and looking it up in the module’s namespace.

frame @ -1 : call to traceback.extract_stack()
frame @ -2 : call to trace()
frame @ -3 : call to A.a()

You can try to create a wrapper/decorator for Aha . I suggest you to read this and this if you don’t know that decorators are.

Something like the following should print out the function name and then call the function.

def wrapper(func): def inner(*args, **kwargs): print("function has been called".format(func.__name__)) return func(*args, **kwargs) return inner @wrapper def f(): print "I'm in the function 
In [16]: f() function f has been called in the function 

Static methods vs Instance methods in Java, Instance method are methods which require an object of its class to be created before it can be called. To invoke a instance method, we have

How to get (sub)class name from a static method in Python?

Replace the staticmethod with a classmethod. This will be passed the class when it is called, so you can get the class name from that.

class Bar(object): @classmethod def bar(cls): # code print cls.__name__ class Foo(Bar): # code pass >>> Bar.bar() Bar >>> Foo.bar() Foo 

If you need to find the class information, the appropriate way is to use @classmethod .

class Bar(object): @classmethod def bar(cls): # code print(cls.__name__) class Foo(Bar): # code pass 

Now your bar method has a reference to the class as cls which is the actual class of the caller. And as shown in the code, cls.__name__ is the name of the class you are looking for.

As option, if you need determine class from staticmethod (not classmethod) I guess following code could be helpful:

class Bar(object): @staticmethod def bar(): pass class Foo(Bar): pass foo_instance = Foo() bar_static_function = foo_instance.bar class_name = bar_static_function.__qualname__.split(".")[0] print(class_name) # Foo 

Passing class/instance attributes to static methods in Python, A static method will not receive self , which is the instance. You do not get a implicit reference to the instance in a static method. You can

Why can a static method change a class object’s attributes?

I think you are misunderstanding the difference between a «self instance» and a regular instance.

In a normal method, you have to specify the self argument:

class Foo1: def bar(*args): print(args) foo1 = Foo1() foo1.bar() # outputs (,) 

That means that inside the Bar method, you have a «self instance» of Foo .

What the staticmethod decorator does, is it takes the foo.bar call, and strips off the self argument:

class Foo2: @staticmethod def bar(*args): print args foo2 = Foo2() foo2.bar() # outputs () 

So, if you pass in a Foo object, it’ll look like this:

This is what you’re doing when you call new_patient.admit_patient(new_patient) .

Note that this is a non-pythonic way of using a staticmethod . Usually, you would use them before you have an instance of the class, calling it on the class itself:

Whereas, trying to do that with a standard method would normally raise an error as it expects a self argument:

The other useful decorator is classmethod , which passes in a class object:

class Foo3: @classmethod def bar(*args): print(args) Foo3.bar() # outputs (,) 

Note that it’s a class rather than an instance .

Python classmethod(), A class method is a method that is bound to a class rather than its object. It doesn’t require creation of a class instance, much like staticmethod. The

Источник

Объяснение @classmethod и @staticmethod в Python

Для новичков, изучающих объектно-ориентированное программирование на Python, очень важно хорошо разбираться в таких понятиях как classmethod и staticmethod для написания более оптимизированного и повторно используемого кода.

Кроме того, даже опытные программисты, работающие на разных языках, часто путают эти два понятия.

В этой статье мы разберем что это такое и какая между ними разница.

staticmethod в Python

@staticmethod – используется для создания метода, который ничего не знает о классе или экземпляре, через который он был вызван. Он просто получает переданные аргументы, без неявного первого аргумента, и его определение неизменяемо через наследование.

Проще говоря, @staticmethod – это вроде обычной функции, определенной внутри класса, которая не имеет доступа к экземпляру, поэтому ее можно вызывать без создания экземпляра класса.

class ClassName: @staticmethod def method_name(arg1, arg2, . ): .

Здесь мы используем декоратор @staticmethod для определения статического метода в Python. Вы можете заметить, что статический метод не принимает self в качестве первого аргумента для метода.

А теперь посмотрим на пример использования.

class Myclass(): @staticmethod def staticmethod(): print('static method called')

Как мы уже говорили, мы можем получить доступ к статическому методу класса без создания экземпляра.

Хотя вызов метода из экземпляра класса тоже возможен.

my_obj = Myclass() my_obj.staticmethod()

Отлично, но когда полезны статические методы?

Статический метод помогает в достижении инкапсуляции в классе, поскольку он не знает о состоянии текущего экземпляра. Кроме того, статические методы делают код более читабельным и повторно используемым, а также более удобным для импорта по сравнению с обычными функциями, поскольку каждую функцию не нужно отдельно импортировать.

class Person(): @staticmethod def is_adult(age): if age > 18: return True else: return False

В приведенном выше примере мы можем проверить, является ли человек взрослым, без инициирование создания экземпляра.

Classmethod в Python

@classmethod – это метод, который получает класс в качестве неявного первого аргумента, точно так же, как обычный метод экземпляра получает экземпляр. Это означает, что вы можете использовать класс и его свойства внутри этого метода, а не конкретного экземпляра.

Проще говоря, @classmethod – это обычный метод класса, имеющий доступ ко всем атрибутам класса, через который он был вызван. Следовательно, classmethod – это метод, который привязан к классу, а не к экземпляру класса.

class Class: @classmethod def method(cls, arg1, arg2, . ): .

В данному случае декоратор @classmethod используется для создания методов класса, и cls должен быть первым аргументом каждого метода класса.

class MyClass: @classmethod def classmethod(cls): print('Class method called')

Функцию classmethod также можно вызывать без создания экземпляра класса, но его определение следует за подклассом, а не за родительским классом, через наследование.

Когда использовать classmethod?

@classmethod используется, когда вам нужно получить методы, не относящиеся к какому-либо конкретному экземпляру, но тем не менее, каким-то образом привязанные к классу. Самое интересное в них то, что их можно переопределить дочерними классами.

Поэтому, если вы хотите получить доступ к свойству класса в целом, а не к свойству конкретного экземпляра этого класса, используйте classmethod.

class MyClass(): TOTAL_OBJECTS=0 def __init__(self): MyClass.TOTAL_OBJECTS = MyClass.TOTAL_OBJECTS+1 @classmethod def total_objects(cls): print("Total objects: ",cls.TOTAL_OBJECTS) # Создаем объекты my_obj1 = MyClass() my_obj2 = MyClass() my_obj3 = MyClass() # Вызываем classmethod MyClass.total_objects()

Теперь, если мы унаследуем этот класс в дочерний класс и объявим там переменную TOTAL_OBJECTS и вызовем метод класса из дочернего класса, он вернет общее количество объектов для дочернего класса.

class MyClass(): TOTAL_OBJECTS=0 def __init__(self): MyClass.TOTAL_OBJECTS = MyClass.TOTAL_OBJECTS+1 @classmethod def total_objects(cls): print("Total objects: ", cls.TOTAL_OBJECTS) # Создаем объекты родительского класса my_obj1 = MyClass() my_obj2 = MyClass() # Создаем дочерний класс class ChildClass(MyClass): TOTAL_OBJECTS=0 pass ChildClass.total_objects()

Заключение

@classmethod используется в суперклассе для определения того, как метод должен вести себя, когда он вызывается разными дочерними классами. В то время как @staticmethod используется, когда мы хотим вернуть одно и то же, независимо от вызываемого дочернего класса.

Также имейте в виду, что вызов @classmethod включает в себя дополнительное выделение памяти, чего нет при вызове @staticmethod или обычной функции.

Источник

Оцените статью