The functionality of isinstance(...); but without an instance? [duplicate] - python

This question already has answers here:
How do I check (at runtime) if one class is a subclass of another?
(10 answers)
Closed 3 years ago.
At runtime, I want to check whether a specified child class is derived from a specified parent class.
With an object instance, it's easy:
def is_related(child_instance, parent_type):
return isinstance(child_instance, parent_type)
Is there some way to do this without having (or creating) an instance of the child but, instead, having a reference to the child's type?
Something like...
def is_related(child_type, parent_type):
return is_child_class(child_type, parent_type)
Provide an implementation for is_child_class will answer this question.
(By comparison, types in C# know about their supertypes. I don't know whether this is also true in Python.)

Let's say that ChildClass is a subclass of ParentClass. Then
issubclass(ChildClass, ParentClass)
would return True

Here is a possible solution:
class A:
pass
class B(A):
pass
issubclass(B, A) # True

This is what you need to define the is_child_class method as:
def is_child_class(child_type, parent_type):
return issubclass(child_type, parent_type)

Related

Get all #properties from a Python Class [duplicate]

This question already has answers here:
In a Python object, how can I see a list of properties that have been defined with the #property decorator?
(5 answers)
Closed 2 years ago.
In Python, how can I get all properties of a class, i.e. all members created by the #property decorator?
There are at least two questions[1, 2] on stackoverflow which confound the terms property and attribute, falsely taking property as a synonym for attribute, which is misleading in Python context. So, even though the other questions' titles might suggest it, they do not answer my question.
[1]: Print all properties of a Python Class
[2]: Is there a built-in function to print all the current properties and values of an object?
We can get all attributes of a class cls by using cls.__dict__. Since property is a certain class itself, we can check which attributes of cls are an instance of property:
from typing import List
def properties(cls: type) -> List[str]:
return [
key
for key, value in cls.__dict__.items()
if isinstance(value, property)
]

Method vs function-valued field in Python [duplicate]

This question already has answers here:
What is the difference between a function, an unbound method and a bound method?
(6 answers)
Closed 2 years ago.
I am switching from MATLAB to Python and numpy and I would like to know if there is any difference between the option to define a class method and the option to the function to a class field (instance variable)? Here is the example:
class MyClass:
def __init__(self, a):
self.a=a #some variable
def add(self,b):
return self.a+b
vs
class MyClass:
def __init__(self, a):
self.a=a #some variable
self.add = lambda b: self.a+b
It works in both cases when I call
my_object=MyClass(2)
print(my_object.add(2)) #prints 4
Are there any differences between these two approaches? Any best practices/downsides?
To me, the first one feels more "proper OOP", but the second one feels more flexible. Or, maybe, the definitions are identical, because of the way Python works under the hood?
The second one can't be overridden and takes a lot more space, because there's a separate function in every instance's __dict__ instead of one function in the class __dict__. (Instance method objects are created and reclaimed on the fly if you do it the normal way, or optimized out entirely in many cases depending on Python version.)

How to declare a variable to be implemented in the subclass in python? [duplicate]

This question already has answers here:
Abstract attributes in Python [duplicate]
(13 answers)
Closed 5 years ago.
Update
Actually, I have tested all the answers, but a feature I want still can't be achieved. Using #property force the subclass to directly declare the property but not something like self.property = xxx in one function. How could I also achieve this?
I mean, if the subclass __get__ the property before __set__, then raise NotImplementedError.
How to declare a variable in the super class which should be implemented in the subclass?
In other word, I want to declare a virtual variable in super class.
class A:
def a(self): # perfect!
raise NotImplementedError("...")
b = raise NotImplementedError("...") #how to declare a variable similar with the function above?
Since Python doesn't really have something called virtual objects, you can mimic in case of methods by explicitly raising exception but in the case of variables, you can either override __init__ or use properties instead of variables.
class A(object):
def __init__(self, *args, **kwargs):
if not hasattr(self, 'b'):
raise NotImplementedError("...")
class B(A):
b = 3
You can use the property decorator. For more information, please check this thread where you can get a detailed answer.

python property decorator [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Real world example about how to use property feature in python?
I have a question about the decorator #property that I've seen in the following code. Could someone be kind enough to completely explain why someone would use the #property decorator? I know #property is equivalent to isActive = property(isActive) but what does the method property actually do to it's parameter? If I were to call the isActive method from the InputCell class what would actually happen? Thanks in advance.
class InputCell(object):
def __init__(self, ix, iy, inputData):
self.ix = ix
self.iy = iy
self.InputData = inputData
#property
def isActive(self):
return self.InputData[self.ix][self.iy]
It's simply syntactic sugar. It allows a method call to look like a variable access or assignment.
One way this can be useful is if you want to change something that previously was a simple variable to something that's actually computed or validated with other code. If you make it a property, you can do this without breaking any existing code. Another way is for caching, lazy initialization, etc., of object attributes.

Python : Difference between static methods vs class method [duplicate]

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?

Categories

Resources