Accessing class variables using class or object? - python-3.x

What is the best practice / difference between accessing a class variable using the class or using a object created by the class?
for example I have the following class and creating an object:
class MyClass():
class_variable = 10
def __init__(self):
self.object_variable = 5
object = MyClass()
I can access the class_variable in two ways:
object.class_variable
myClass.class_variable
I cannot see any difference as these two possibilities will always return the same value.

Related

Python create dynamic class and set multi bases from imported module

I found several example here, but is not what exactly looking for, will try to explain here
from this answer tried to achieve my result but is not what looking for
How can I dynamically create derived classes from a base class
i have a module that holds many classes
importing the module
import importlib
# are awalable many classes here
forms = importlib.import_module('my_forms')
Now, based on forms i need to create a new class and add bases to my new class all classes that are availabe in forms
this what i tried, but can not find a way to assign the bases
import inspect
def create_DynamicClass():
class DynamicClass(BaseClass):
pass
for form_name, class_name in inspect.getmembers(forms):
for i in class_name():
# here the code to added all bases to DynamicClass
return DynamicClass()
example how my_forms module looks
class MyClass1(BaseClass):
attr1 = 1
attr2 = 2
#coroutine
def prepare(self):
# some code for each class
class MyClass2(BaseClass):
attr3 = 3
attr4 = 4
#coroutine
def prepare(self):
# some code for each class
class MyClass3(BaseClass):
attr5 = 5
attr6 = 6
#coroutine
def prepare(self):
# some code for each class
The result that i want to achieve is the following, will make a static class to show desired result but need to be dynamic
I need to create my class dynamic because in my_forms module can be any amount of classes
# inherits all classes from my_forms module
class MyResultClass(MyClass1, MyClass2, MyClass3):
# here get all available attributes from all classes
#coroutine
def prepare(self):
# as well need each prepare function for each class as well
yield MyClass1().prepare()
yield MyClass2().prepare()
yield MyClass3().prepare()
Simply declare the dynamic class with all of your base classes. To do so, put all of your base classes in a list, and unpack the list in the class definition statement with the * operator like this:
def createClass(baseClasess):
class NewClass(*baseClasses):
pass
return NewClass
DynamicClass = createClass([class1, class2, ...])
i have managed to find a solution, will post here, if any recommendation to make it better will appreciate
forms = importlib.import_module('my_forms')
class Form(BaseForm):
#coroutine
def prepare(self):
for form_name, class_name in inspect.getmembers(forms, inspect.isclass):
try:
yield class_name().prepare()
except TypeError:
continue
def createClass(meta):
for form_name, class_name in inspect.getmembers(forms, inspect.isclass):
try:
Form.__bases__ += (class_name, )
for field in class_name():
field_type = fl.SelectField() if hasattr(field, 'choices') else fl.StringField()
setattr(Form, field.name, field_type)
except TypeError:
continue
return Form(meta=meta)

Access a Class object from a class static variable in python3?

Is it possible to access a class object or its inner class object from a class static variable in python3?
class OuterClass:
all_subclasses = {
# is it possible to access the OuterClass from a class static variable
'innerclass1': OuterClass.InnerClass1
}
#classmethod
isInnerClass(cls, identifier: str):
return identifier.lower() in cls.all_subclasses
class InnerClass1:
def __init__(self):
pass
If not, what will be alternative for this?
You can refer to attributes of the class directly in the class definition, as long as the reference comes after the definition:
class A:
class B:
pass
x = B
print(A.x)
# <class '__main__.A.B'>
This has some caveats. For reasons that are very complicated, you can't use class attributes directly in a comprehension in the class definition:
class A:
class B:
pass
x = [B for _ in range(5)] # NameError: name 'B' is not defined
You also can't refer to the class itself in it's own definition:
class A:
x = A # NameError: name 'A' is not defined
This is because class definition is basically another way of creating a type object
class A:
x = 1
A = type('A', (object,), {'x': 1})
And it makes total sense both that you can't use an object before it's created and that you can't refer to it by a name it hasn't been assigned to yet.
It's important to note that this all applies only to the class definition itself, that is to say all of the code that gets executed directly as the class is created. Code that gets executed later, like method definitions, can refer to the class like any other code or through type(self)

python class not recognize class declared inside of her

this question must be a stupid one but important one and couldn't find any discussion about this in stackoverflow.
I'm trying to declare a class (lets say class 'B') inside another class (lets say 'A'), and use that class('B') in a method of class 'A', but for some reason in python you cannot declare an object member of class type that is declared in the same class.
why is that the case? in C you can access to the inner class from a method of the outside class without any problem...
(my intention that is only class A will ever need a member of type class B and i want only A to be able to find out that such a class like B...)
what is the proper way to do so in python?
class A:
def __init__(self):
self.B_object = B() # error 'unresolved refernace B'
class B:
def __init(self):
pass
class A:
def __init__(self):
self.B_object = A.B()
class B:
def __init(self):
pass
Try this
if you want to make B class private you can try this
class A:
def __init__(self):
self.__B_object = A.__B()
class __B:
def __init__(self):
pass

Check whether an instance of a class exists at runtime

I need to know how to check if an instance of a given class exists at runtime. So I need to make interactions between this instance and other classes. There is no relationship between these classes (composition, aggregation, and inheritance). So how do you get the reference for this class if it exists?
If you just want to know if (or how many times) a class has been instantiated, just keep a counter in the class:
class Foo:
counter = 0
def __init__(self):
Foo.counter += 1
Foo()
print(Foo.counter)
Alternatively, if you want to keep a handle on all the instances (by reference), instead store self:
class Foo:
classes = []
def __init__(self):
Foo.classes.append(self)
Foo()
print(Foo.classes[0])

Implement child class level variable in abstract base class [duplicate]

This question already has answers here:
Counting instances of a class?
(7 answers)
How to count the number of instance of a custom class?
(1 answer)
Closed 4 years ago.
I have made an abstract base class using metaclass=ABCMeta to implement some default methods and properties that all its derived classes should have, something like this:
class BaseClass(metaclass=ABCMeta):
def __init__(self):
self.params = OrderedDict()
# some function all children must implement
#abstractmethod
def fn():
pass
# some property all children will have
#property
def n_params(self):
return len(self.params)
Now, I want to count how many instances of each derived class are created, because I want to print their name with a number. I can easily implement it like this:
class ChildClass(BaseClass):
# nr of instances of ChildClass
_n = 0
def __init__(self, mu, sigma, amp):
# initialize ABC
super().__init__()
ChildClass._n += 1
self.name = f'ChildClass {ChildClass._n}'
# must be overridden by each child class
#staticmethod
def fn(name):
# do stuff
print(f'hello {name}')
However, I need to implement this in each class that derives from BaseClass separately. It would be much more elegant to implement it in BaseClass itself.
I am looking for something that works like the opposite of super(), maybe something like this:
class BaseClass(metaclass=ABCMeta):
# instance counter for derived classes
child()._n = 0
def __init__(self):
self.params = OrderedDict()
child()._n += 1
Can I implement a class level variable ChildClass._n in BaseClass? And if so, how can I access that variable in BaseClass.__init__?
Edit:
To clarify: I already have a base class, from which I derive many other child classes. The fact that all these classes share many properties is one of the main reasons I decided to use a base class in the first place. It thus seems superfluous to need to implement something as simple as an instance counter separately in each derived class.
Accessing a child class variable seems to be already adressed here. The question that remains is, how do I define a class level variable in my abstract base class, that is different for each child class.

Resources