Get the full name of a nested class - python

Given a nested class B:
class A:
class B:
def __init__(self):
pass
ab = A.B()
How can I get the full name of the class for ab? I'd expect a result like A.B.

You could get the fully qualified name, __qualname__, of its __class__:
>>> ab.__class__.__qualname__
'A.B'
Preferably by using type (which calls __class__ on the instance):
>>> type(ab).__qualname__

Related

Get overridden functions of subclass

Is there a way to get all overriden functions of a subclass in Python?
Example:
class A:
def a1(self):
pass
def a2(self):
pass
class B(A):
def a2(self):
pass
def b1(self):
pass
Here, I would like to get a list ["a2"] for an object of class B (or for the class object itself) since class B overrides only a single method, namely a2.
You can access the parent classes with cls.__bases__, find all attributes of the parents with dir, and access all the attributes of the class itself with vars:
def get_overridden_methods(cls):
# collect all attributes inherited from parent classes
parent_attrs = set()
for base in cls.__bases__:
parent_attrs.update(dir(base))
# find all methods implemented in the class itself
methods = {name for name, thing in vars(cls).items() if callable(thing)}
# return the intersection of both
return parent_attrs.intersection(methods)
>>> get_overridden_methods(B)
{'a2'}
You can make use of the __mro__ tuple, which holds the method resolution order.
For your example:
>>> B.__mro__
( <class '__main__.B'>, <class '__main__.A'>, <class 'object'>)
So you could loop over that tuple and check if a B method is also in one of the other classes.
class A:
def a1(self):
pass
def a2(self):
pass
class B(A):
def a2(self):
super().a2()
pass
def b1(self):
pass
obj = B()
obj.a2() # ***first give the output of parent class then child class***

Private Class Variables in Python?

I'd like to be able to extend a class without inheriting one of the class variables.
Given this scenario:
class A:
aliases=['a','ay']
class B(A):
pass
print(B.aliases)
I would rather get an error that B has not defined the aliases variable rather than have B accidentally called ay.
One could imagine a solution where aliases becomes a member of the instantiated object (self.aliases) and is set in __init__ but I really want to be able to access the aliases using the cls object rather than an instance of the class.
Any suggestions?
Python does not have REALY private attributes. But you can define it with a double underscore (__):
class A:
__aliases=['a','ay']
class B(A):
pass
print(B.__aliases) # yields AttributeError
But you still will be able to access it with:
print(B._A__aliases)
This is kindof a ganky work around but here you go:
class K:
def __init__(self):
self.mems = dir(self)
def defaultMembers():
k = K()
return(k.mems)
class A:
aliases=['a','ay']
class B(A):
def __init__(self):
for k in set(dir(self))-set(defaultMembers()):
print("removing "+k)
setattr(self, k, None)
a = A()
b = B()
print(b.aliases)
#None
print(a.aliases)
#['a','ay']
I guess all you really need is the setattr(self, "aliases", None) still this results in a None and not a non-variable. Unfortunately calsses don't support deletion because I tried to use del first.

call a method of class instance located inside a python list

I have following classes in python:
QueryElement as a root class
ElemMatch and GT which inherit from the root.
I have a list in ElemMatch class which is supposed to have instances of QueryElement.
My problem is in invoking a method called compute from the instances inside the list, in ElemMatch class(compute method). The type of object inside the list is not identified by Python, and I do not know how to assign a type to the list. I do not have such a problem in Java since I could 'cast' to a type I like, but here I do not know how to solve it.
I appreciate if you could help.
class QueryElement(object):
__metaclass__ = abc.ABCMeta
#abc.abstractmethod
def addQueryElement(self, queryElement):
raise NotImplementedError( "Should have implemented this" )
#abc.abstractmethod
def compute(self):
raise NotImplementedError( "Should have implemented this" )
class ElemMatch(QueryElement):
def __init__(self):
self._queryElements = []
def addQueryElement(self, queryElement):
self._queryElements.append(queryElement)
def compute(self):
elemMatch = {}
if len (self._queryElements) > 0:
elemMatch['e'] = self._queryElements[0].compute()
return elemMatch
class GT(QueryElement):
def __init__(self):
print 'someThing'
def addQueryElement(self, queryElement):
return None
def compute(self):
print 'compute GT!'
class PALLAS(object):
def foo(self):
gt = GT()
elemMatch = ElemMatch()
elemMatch.addQueryElement(gt)
elemMatch.compute()
p = PALLAS()
p.foo()
In Python, the objects, not the names referring to them, are typed. If the object has a compute method, you can call it, regardless of what the type of the object is.
A quick example:
class A(object):
def foo(self):
print "I'm an A"
class B(object):
def foo(self):
print "I'm a B"
lst = [A(), A(), B(), A(), B()]
for l in lst:
l.foo()
Each element of lst is either an instance of A or of B. Since both have a method named foo, you don't have to know the type of the object referenced by l each time through the loop; the lookup of foo will find the correct method.
This is commonly referred to as duck typing; if l looks like a duck and acts like a duck (i.e., if it has a method foo), then it is a duck (i.e., then we can call the method foo).

How to keep track of class instances?

Toward the end of a program I'm looking to load a specific variable from all the instances of a class into a dictionary.
For example:
class Foo():
def __init__(self):
self.x = {}
foo1 = Foo()
foo2 = Foo()
...
Let's say the number of instances will vary and I want the x dict from each instance of Foo() loaded into a new dict. How would I do that?
The examples I've seen in SO assume one already has the list of instances.
One way to keep track of instances is with a class variable:
class A(object):
instances = []
def __init__(self, foo):
self.foo = foo
A.instances.append(self)
At the end of the program, you can create your dict like this:
foo_vars = {id(instance): instance.foo for instance in A.instances}
There is only one list:
>>> a = A(1)
>>> b = A(2)
>>> A.instances
[<__main__.A object at 0x1004d44d0>, <__main__.A object at 0x1004d4510>]
>>> id(A.instances)
4299683456
>>> id(a.instances)
4299683456
>>> id(b.instances)
4299683456
#JoelCornett's answer covers the basics perfectly. This is a slightly more complicated version, which might help with a few subtle issues.
If you want to be able to access all the "live" instances of a given class, subclass the following (or include equivalent code in your own base class):
from weakref import WeakSet
class base(object):
def __new__(cls, *args, **kwargs):
instance = object.__new__(cls, *args, **kwargs)
if "instances" not in cls.__dict__:
cls.instances = WeakSet()
cls.instances.add(instance)
return instance
This addresses two possible issues with the simpler implementation that #JoelCornett presented:
Each subclass of base will keep track of its own instances separately. You won't get subclass instances in a parent class's instance list, and one subclass will never stumble over instances of a sibling subclass. This might be undesirable, depending on your use case, but it's probably easier to merge the sets back together than it is to split them apart.
The instances set uses weak references to the class's instances, so if you del or reassign all the other references to an instance elsewhere in your code, the bookkeeping code will not prevent it from being garbage collected. Again, this might not be desirable for some use cases, but it is easy enough to use regular sets (or lists) instead of a weakset if you really want every instance to last forever.
Some handy-dandy test output (with the instances sets always being passed to list only because they don't print out nicely):
>>> b = base()
>>> list(base.instances)
[<__main__.base object at 0x00000000026067F0>]
>>> class foo(base):
... pass
...
>>> f = foo()
>>> list(foo.instances)
[<__main__.foo object at 0x0000000002606898>]
>>> list(base.instances)
[<__main__.base object at 0x00000000026067F0>]
>>> del f
>>> list(foo.instances)
[]
You would probably want to use weak references to your instances. Otherwise the class could likely end up keeping track of instances that were meant to have been deleted. A weakref.WeakSet will automatically remove any dead instances from its set.
One way to keep track of instances is with a class variable:
import weakref
class A(object):
instances = weakref.WeakSet()
def __init__(self, foo):
self.foo = foo
A.instances.add(self)
#classmethod
def get_instances(cls):
return list(A.instances) #Returns list of all current instances
At the end of the program, you can create your dict like this:
foo_vars = {id(instance): instance.foo for instance in A.instances}
There is only one list:
>>> a = A(1)
>>> b = A(2)
>>> A.get_instances()
[<inst.A object at 0x100587290>, <inst.A object at 0x100587250>]
>>> id(A.instances)
4299861712
>>> id(a.instances)
4299861712
>>> id(b.instances)
4299861712
>>> a = A(3) #original a will be dereferenced and replaced with new instance
>>> A.get_instances()
[<inst.A object at 0x100587290>, <inst.A object at 0x1005872d0>]
You can also solve this problem using a metaclass:
When a class is created (__init__ method of metaclass), add a new instance registry
When a new instance of this class is created (__call__ method of metaclass), add it to the instance registry.
The advantage of this approach is that each class has a registry - even if no instance exists. In contrast, when overriding __new__ (as in Blckknght's answer), the registry is added when the first instance is created.
class MetaInstanceRegistry(type):
"""Metaclass providing an instance registry"""
def __init__(cls, name, bases, attrs):
# Create class
super(MetaInstanceRegistry, cls).__init__(name, bases, attrs)
# Initialize fresh instance storage
cls._instances = weakref.WeakSet()
def __call__(cls, *args, **kwargs):
# Create instance (calls __init__ and __new__ methods)
inst = super(MetaInstanceRegistry, cls).__call__(*args, **kwargs)
# Store weak reference to instance. WeakSet will automatically remove
# references to objects that have been garbage collected
cls._instances.add(inst)
return inst
def _get_instances(cls, recursive=False):
"""Get all instances of this class in the registry. If recursive=True
search subclasses recursively"""
instances = list(cls._instances)
if recursive:
for Child in cls.__subclasses__():
instances += Child._get_instances(recursive=recursive)
# Remove duplicates from multiple inheritance.
return list(set(instances))
Usage: Create a registry and subclass it.
class Registry(object):
__metaclass__ = MetaInstanceRegistry
class Base(Registry):
def __init__(self, x):
self.x = x
class A(Base):
pass
class B(Base):
pass
class C(B):
pass
a = A(x=1)
a2 = A(2)
b = B(x=3)
c = C(4)
for cls in [Base, A, B, C]:
print cls.__name__
print cls._get_instances()
print cls._get_instances(recursive=True)
print
del c
print C._get_instances()
If using abstract base classes from the abc module, just subclass abc.ABCMeta to avoid metaclass conflicts:
from abc import ABCMeta, abstractmethod
class ABCMetaInstanceRegistry(MetaInstanceRegistry, ABCMeta):
pass
class ABCRegistry(object):
__metaclass__ = ABCMetaInstanceRegistry
class ABCBase(ABCRegistry):
__metaclass__ = ABCMeta
#abstractmethod
def f(self):
pass
class E(ABCBase):
def __init__(self, x):
self.x = x
def f(self):
return self.x
e = E(x=5)
print E._get_instances()
Another option for quick low-level hacks and debugging is to filter the list of objects returned by gc.get_objects() and generate the dictionary on the fly that way. In CPython that function will return you a (generally huge) list of everything the garbage collector knows about, so it will definitely contain all of the instances of any particular user-defined class.
Note that this is digging a bit into the internals of the interpreter, so it may or may not work (or work well) with the likes of Jython, PyPy, IronPython, etc. I haven't checked. It's also likely to be really slow regardless. Use with caution/YMMV/etc.
However, I imagine that some people running into this question might eventually want to do this sort of thing as a one-off to figure out what's going on with the runtime state of some slice of code that's behaving strangely. This method has the benefit of not affecting the instances or their construction at all, which might be useful if the code in question is coming out of a third-party library or something.
Here's a similar approach to Blckknght's, which works with subclasses as well. Thought this might be of interest, if someone ends up here. One difference, if B is a subclass of A, and b is an instance of B, b will appear in both A.instances and B.instances. As stated by Blckknght, this depends on the use case.
from weakref import WeakSet
class RegisterInstancesMixin:
instances = WeakSet()
def __new__(cls, *args, **kargs):
o = object.__new__(cls, *args, **kargs)
cls._register_instance(o)
return o
#classmethod
def print_instances(cls):
for instance in cls.instances:
print(instance)
#classmethod
def _register_instance(cls, instance):
cls.instances.add(instance)
for b in cls.__bases__:
if issubclass(b, RegisterInstancesMixin):
b._register_instance(instance)
def __init_subclass__(cls):
cls.instances = WeakSet()
class Animal(RegisterInstancesMixin):
pass
class Mammal(Animal):
pass
class Human(Mammal):
pass
class Dog(Mammal):
pass
alice = Human()
bob = Human()
cannelle = Dog()
Animal.print_instances()
Mammal.print_instances()
Human.print_instances()
Animal.print_instances() will print three objects, whereas Human.print_instances() will print two.
Using the answer from #Joel Cornett I've come up with the following, which seems to work. i.e. i'm able to total up object variables.
import os
os.system("clear")
class Foo():
instances = []
def __init__(self):
Foo.instances.append(self)
self.x = 5
class Bar():
def __init__(self):
pass
def testy(self):
self.foo1 = Foo()
self.foo2 = Foo()
self.foo3 = Foo()
foo = Foo()
print Foo.instances
bar = Bar()
bar.testy()
print Foo.instances
x_tot = 0
for inst in Foo.instances:
x_tot += inst.x
print x_tot
output:
[<__main__.Foo instance at 0x108e334d0>]
[<__main__.Foo instance at 0x108e334d0>, <__main__.Foo instance at 0x108e33560>, <__main__.Foo instance at 0x108e335a8>, <__main__.Foo instance at 0x108e335f0>]
5
10
15
20
(For Python)
I have found a way to record the class instances via the "dataclass" decorator while defining a class. Define a class attribute 'instances' (or any other name) as a list of the instances you want to record. Append that list with the 'dict' form of created objects via the dunder method __dict__. Thus, the class attribute 'instances' will record instances in the dict form, which you want.
For example,
from dataclasses import dataclass
#dataclass
class player:
instances=[]
def __init__(self,name,rank):
self.name=name
self.rank=rank
self.instances.append(self.__dict__)

Python: How to access parent class object through derived class instance?

I'm sorry for my silly question, but... let's suppose I have these classes:
class A():
msg = 'hehehe'
class B(A):
msg = 'hohoho'
class C(B):
pass
and an instance of B or C. How do I get the variable 'msg' from the parent's class object through this instance?
I've tried this:
foo = B()
print super(foo.__class__).msg
but got the message: "TypeError: super() argument 1 must be type, not classobj".
You actually want to use
class A(object):
...
...
b = B()
bar = super(b.__class__, b)
print bar.msg
Base classes must be new-style classes (inherit from object)
If the class is single-inherited:
foo = B()
print foo.__class__.__bases__[0].msg
# 'hehehe'
If the class is multiple-inherited, the question makes no sense because there may be multiple classes defining the 'msg', and they could all be meaningful. You'd better provide the actual parent (i.e. A.msg). Alternatively you could iterate through all direct bases as described in #Felix's answer.
Not sure why you want to do this
>>> class A(object):
... msg = 'hehehe'
...
>>> class B(A):
... msg = 'hohoho'
...
>>> foo=B()
>>> foo.__class__.__mro__[1].msg
'hehehe'
>>>
As msg is a class variable, you can just do:
print C.msg # prints hohoho
If you overwrite the variable (as you do in class B), you have to find the right parent class. Remember that Python supports multiple inheritance.
But as you define the classes and you now that B inherits from A you can always do this:
class B(A):
msg = 'hohoho'
def get_parent_message(self):
return A.msg
UPDATE:
The most reliable thing would be:
def get_parent_attribute(instance, attribute):
for parent in instance.__class__.__bases__:
if attribute in parent.__dict__:
return parent.__dict__[attribute]
and then:
foo = B()
print get_parent_attribute(foo, 'msg')
Try with:
class A(object):
msg = 'hehehe'
EDIT:
For the 'msg' attribute you would need:
foo = B()
bar = super(foo.__class__, foo)
print bar.msg
#for B() you can use __bases__
print foo.__class__.__bases__[0].msg
But this is not gonna be easy when there are multiple base classes and/or the depth of hierarchy is not one.

Categories

Resources