This question already has answers here:
What are metaclasses in Python?
(25 answers)
Closed 3 years ago.
When browsing the source code for the django_filters library, I found a class declaration syntax that I've never seen before: inheritance with arguments. I could not find an explanation in the official python class tutorial.
Here is the source, snippet below:
class FilterSet(BaseFilterSet, metaclass=FilterSetMetaclass):
pass
what does metaclass=FilterSetMetaclass in the class definition do?
There are two uses for keyword arguments in the list of base classes.
The metaclass argument is used specially to indicate which metaclass (instead of type) to use to create the class. (In Python 2, this was done by assigning a value to the class attribute __metaclass__ in the body of the class statement.)
A class statement is essentially a call to the metaclass.
class Foo(metaclass=Bar):
pass
is equivalent to Foo = Bar('Foo', (), {}). The default metaclass is type, that is
class Foo():
pass
is equivalent to
class Foo(metaclass=type):
pass
Other keyword arguments are passed along to __init_subclass__.
Both of the above are simplifications; see Customizing Class creation for more details.
Related
This question already has answers here:
Does the #staticmethod decorator do anything?
(2 answers)
Closed 3 years ago.
Given that the following code runs without error, why is the staticmethod decorator necessary? What is it actually doing?
class Foo:
def say_hi(name):
print(f'Hello {name}.')
#staticmethod
def say_bye(name):
print(f'See ya later, {name}.')
my_name = 'Bar...t'
Foo.say_hi(my_name)
Foo.say_bye(my_name)
Static methods, much like class methods, are methods that are bound to a class rather than its object.
They do not require a class instance creation. So, they are not dependent on the state of the object.
The difference between a static method and a class method is:
Static method knows nothing about the class and just deals with the parameters.
Class method works with the class since its parameter is always the class itself.
https://www.programiz.com/python-programming/methods/built-in/staticmethod
This question is related to this question about PyTables metaclasses. I was trying to subclass the IsDescription metaclass in PyTables, to define the shape of the Column by a variable:
import tables
class MyClass(tables.IsDescription):
def __init__(self, param):
var1 = tables.Float64Col(shape=(param))
MyClass1 = MyClass(12)
This throws the error: TypeError: object.__new__() takes no parameters. Using self.var1 = ... gives the same error.
In this SO question the same error is reported, and the reason is attributed to the fact that IsDescription is a metaclass.
My question (which is not answered at the linked question, and I haven't been able to find anything by Googling) is: why do metaclasses prohibit this functionality? Is it specific to this metaclass, or generic for all metaclasses?
This is generic to all metaclasses.
In fact a metaclass is instanciated when a class is being created and the parameters passed are always the same, and determine by python.
Those are :
The name of the class to create
The list of inherited classes for this class. It's a tuple of class reference. By default, for new-style class it's object
The dictionary of all fields of the class to be created
You cannot pass you parameters here as this call is done automatically by the python interpreter. In python 2, a metaclass is defined as a __metaclass__ attribute in the class itself, whereas it's a argument in the definition in the class in Python 3.
The __new__ method of the metaclass is called just before the __init__ method of your class and so, takes the same arguments as your class. You can change the behavior of your class at initialization in the metaclass rather than in the constructor for instance.
If you want to define arguments to a metaclass, you can for example use some specific fields to be defined in the class to be defined. You can also write a function that will act like a metaclass to create a class for you, and you will be able to add parameters to that function. But I don't know PyTables and your exact requirements or possibilities.
This question already has answers here:
Why do Python classes inherit object?
(6 answers)
Closed 6 years ago.
When you declare a class in python, I often see (object) written next to the class name.
class someClass(object):
def __init__(self, some_variable):
...
...
Is this same as writing below?
class someClass: # didn't write (object) here.
def __init__(self, some_variable):
...
...
I don't really see any difference in terms of how they function. Is it just a way to clarify that someClass is a subclass of object? and is it a good practice to explicitly write object when I make a class?
In Python 2, making someClass a subclass of object turns someClass into a "new-style class," whereas without (object) it's just a "classic class." See the docs or another question here for information on the differences between them; the short answer is that you should always use new-style classes for the benefits they bring.
In Python 3, all classes are "new-style," and writing (object) is redundant.
In python 3.x, they are the same, when you declare:
class C:
def __init__(self):
...
it inherits from object implicitly.
For more information visit this.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is the difference between #staticmethod and #classmethod in Python?
I am learning OOP in python and came to know about these two methods
It seems that the difference in terms of syntax is that class methods are implicitly passed the class they belong to as their first parameter
class Circle:
all_circles = [] # class variable
#staticmethod
def total_area():
for c in Circle.all_circles: # hardcode class name
# do somethig
#classmethod
def total_area(cls):
for c in cls.all_circles: # no hardcode class name
# do something
I see class method as more flexible since we don't hardcode the class
Question:
- Is it even a question which one is better? #staticmethod or #classmethod?
- what are the scenarios suitable to use of each one of these methods?
A classmethod gets passed the class 'cls' that it was called upon. For more details see: What is the difference between #staticmethod and #classmethod in Python?
This question already has answers here:
Why do Python classes inherit object?
(6 answers)
Closed 5 years ago.
In python class declaration I can declare a class by few ways. What is a difference between following samples?
class MyClass:
def __init__(self)
pass
class MyClass(object):
def __init__(self)
pass
The second declaration creates a new-style class. A new-style class is derived from a built-in type, in this case an object. This was introduced in python 2.2 in an effort to unify classes and types. For backward compatibility old-style classes are still the default
Additional read: http://docs.python.org/release/2.2.3/whatsnew/sect-rellinks.html
The second way creates a "new-style" class. Documentation is admittedly a bit lacking, as mentioned in a couple places on the python website Python Guide 3.3, and here. There's also an essay describing their design by Python's creator (Guido van Rossum), but it's not strictly documentation.