Can a class variable of say, class Foo be a Foo object itself?
For example, I'm trying to build a class for the finite field of order 11, and I want a chosen generator (2) to be associated with this class an instance.
What I have in mind:
class FiniteField11:
generator = FiniteField11(2)
def __init__(self, element):
self.elt = element
This does not compile; I have a NameError: name 'FiniteField11' is not defined.
I realize that there is a chicken-or-egg first problem here, but is there a way to achieve what I want?
Apologies if this is a duplicate, but I can't find one.
You can do something like this:
class FiniteField11:
def __init__(self, element):
self.elt = element
FiniteField11.generator = FiniteField11(2)
Your code fails because FiniteField11 was not defined when the class defintion was parsed.
Yes it can, but the name doesn't exist until the class statement finishes. Therefore, you have to set this class variable after creating the class, perhaps just below the class block or in the instance initializer.
Related
I am trying to access a class instance. I can't assign the class to a variable when I load it and then use it because I need to access the class based on what the user enters.
i.e: user goes to link website.com/classes/y, I need to access the instance with the name y.
I already handle the link and can get "y" or whatever the user entered by itself.
I have the class code as follows:
class LoadModel:
existing_models = []
def __init__(self, model_path):
self.name = model_path.parent.name
self.__class__.existing_models.append(self.name)
For now, I can verify if the class exists using the existing_models list, but how will I be able to access it using the self.name?
I want to access it using LoadModel.name.
It sounds like you want to keep a dictionary of model names to instances. You could do that with something like:
class LoadModel:
modelsByName = {}
def __init__(self, model_path):
self.name = model_path.parent.name
self.modelsByName[self.name] = self
Furthermore if you wanted to access an instance named name as LoadModel.name you could could add
setattr(self.__class__, self.name, self)
to __init__. Or if you were looking up by string (which it sounds like you might be) then you would just do LoadModel.modelsbyName[name].
Note also that you don't need to use self.__class__ when accessing members of the class that you have not assigned within the instance, and since you're only accessing the dictionary object defined in the class, you can use the reference inherited by the instance (self.modelsByName) instead of accessing the class explicitly (self.__class__.modelsByName).
I want use a class master to control status flag to every class which I want to maintain.
But I only find one way to dynamic add function and var like below.(staticmethod and classmethod don't work)
In my case,simple variable like integer ,float,bool can't call by object sharing
I do some research from link below, there are two ways to overcome this problem => one element list or self-defined class
Passing an integer by reference in Python
I wish can find a way perfectly inheritance just like class A(Master):
or instance_a = A(),some_fun(instance_a,Master)
help me to inheritance when creat instance
Do any one know how to achieve that
class A():
pass
class Master():
g_list = []
g_var = 0
def test_method(self,val):
print('test',val)
m_attr_list = [i for i in Master.__dict__.keys() if not i.startswith('__')]
for name in m_attr_list:
setattr(A, name, getattr( Master, name))
I have a class with a method. Now, I put that class inside a list.
When I'm trying to print a method, I do:
print(listname[pointer].method)
But when I compile it says that objects does not support indexation.
The exact code goes like this:
class hero():
def __init__(self, heroname):
self.h=heroname
herolist=[]
herolist.append(hero)
print(herolist[0].h)
I'm expecting that the code will print the hero name, but it doesn't. What am I doing wrong?
EDIT:
Sorry, I forgot to show it in the code but outside of the class I did instantiate the object I am trying to call. To be exact, I did something like:
heroone=hero()
heroone.h='jude'
You have a few problems. First of all, the name of the initialization method is __init__ (two underscores on each side), not ___init___. Second, by appending hero you are appending the class itself. The class itself does not have an h attribute. Only instances of it will have an h attribute, because __init__ is only called when you create an instance. Third, you forgot the self argument in your __init__ method. And fourth, you apparently wrote __init__ to expect a "heroname" argument, but you don't pass any such argument. (You don't pass any arguments, since you never instantiate the class.)
Try this:
class hero():
def __init__(self, heroname):
self.h = heroname
herolist=[]
herolist.append(hero('Bob the Hero'))
print(herolist[0].h)
You store the class definition, not an instanced objet, which means that heroname doesn't have a value. You could write :
herolist.append(hero('Achile'))
and your example will work as expected.
You are using three _ with init method because of which constructor is not called.
two _ are needed on both side init.
To assign name to h pass it to init method.
Use CamelCase to namethe class
Below is working code:
class Hero():
def __init__(self, heroname):
self.h = heroname
herolist=[]
herolist.append(Hero('Dude'))
print(herolist[0].h)
Do like this:-
class Hero():
def __init__(self, heroname):
self.h=heroname
herolist=[]
Now you can do:
h1 = Hero('jude')
herolist.append(h1)
print herolist[0].h
or even simpler:
herolist.append(Hero('Hero'))
print herolist[0].h
I've been trying to comprehend python's implementation of OOP.
Essentially I need something which is a superclass that defines some global attributes that al l other classes use as input for their methods. Eg:
This is how i thought it should be done:
class One():
def __init__(self, name):
self.name = name
class Two(One):
def __init__(self, name): # name from class one...
One.__init__(self, name)
def method_using_name_from_one(self, name_from_one):
return name_from_one
I guess that I could do this by just declaring all the methods in class Two as in methods of class one, but I'd much prefer to have them separated. So to recap: I want the parameters for the method in class two to use the attributes declared in class One. So essentially I want to pass in an instantiated object as the parameter arguments for class Two methods.
When you say
class Two(One):
One isn't a parameter of class Two. That means class Two inherits from class One. In other words, unless you override a method, it gets everything class One has. edit: When I say this, I mean parameters and functions, I don't mean an instance of the class. Since you have:
def __init__(self, name): # name from class one...
One.__init__(self, name)
self.name is in class Two. In other words, you could just say...
def method_using_name_from_one(self):
return self.name
One thing I would suggest is changing your class One declaration to:
class One(object):
This means it inherits from object, it doesn't mean it's getting passed an object :)
Is this what you meant? Maybe I didn't understand correctly.
If you want the name parameter from One, you could say
def method_using_name_from_one(self, oneInstance):
return oneInstance.name
i have a case where i create a class inside an outer function and then return that class. the class has a specified parent class. i would like that class variable to be accessible by class methods on the parent class, these methods are called at class initialization time. in summary, i need to be able to set a class variable (not hardcoded) so that it is available before initializing other, hardcoded class variables.
here's some sample code to make that clearer:
class Parent(object):
class_var = None
#classmethod
def get_class_var_times_two(cls):
return cls.class_var * 2
def outer_function(class_var_value):
class Child(Parent):
other_var = Parent.get_class_var_times_two() # <-- at this point, somehow Child's class_var is set to class_var_value
Not sure if this is even possible in python. Maybe class_var_value doesn't need to be passed through the outer function. I tried using metaclasses and forcing the variable through in the class attribute dictinoary, but couldn't figure out how to set class_var on Child early enough so that it was set prior to initializing other_var. If that was possible, then this would all work. Any thoughts are appreciated!
Edit: also considered making other_var a lazy property, but that isn't an option for my use case.
Calling Parent.get_class_var_times_two() calls the function with cls = Parent, and so consequently the value of Parent.class_var will be used (regardless of what context you call the function from).
So, what you want to do is call Child.get_class_var_times_two(). Trouble is, Child doesn't get defined until the class block finishes. You therefore need to do something like this (assuming you don't use a metaclass):
def outer_function(class_var_value):
class Child(Parent):
class_var = class_var_value
Child.other_var = Child.get_class_var_times_two()