I am trying to add a method to an existing Python scipy.stats class but it is generating a _construct_docstrings error.
import scipy.stats as stats
class myPoisson(stats.poisson) :
def myMethod(var, **kwargs) :
return var
I have tried adding an __init__ method with a call to super().__init__(self) but this has not changed the error.
What am I missing for extending existing Python classes?
hopefully the following example helps you out.
def myMethod(var, **kwargs):
return var
stats.poisson.myMethod = myMethod
stats.poisson.myMethod(2)
Refer to Adding a Method to an Existing Object Instance for further details on the topic.
Scipy.stats distributions are instances, not classes (for historic reasons). Thus, you need to inherit from e.g. poisson_gen, not poisson. Better still, inherit from rv_continuous or rv_discrete directly. See the docstring of rv_continuous for some info on subclassing distributions
Related
I have a Class Factory that generates classes with dynamic name assignment
I like to be able to access them from other modules which import a package A
currently I am loading the classes into a dictionary and updating the vars() of the init.py which to me seems not like a good idea, is there a better way of doing it?
class Model_Factory:
def __init__(self,list_of_names:list):
self._models={}
for name in list_of_names:
self.models[name]=Model_Factory.create_model(name)
#property
def models(self):
return self._models
#classmethod
def create_model(cls,cls_name):
def __init__(self, **kwargs):
super(type(self),self).__init__( **kwargs)
pass
return type(snake_case(cls_name), (parent),
{'__init__': __init__,
'aomething' : 'something',
'attribute_name':'value'})
then inside the package A's init.py
import whatever
some line of code
dic=Model_Factory().models
vars().update(dic)
Then when I want to access those classes all I have to do is to
from A import Dynamically_Created_Class_Name
This works perfectly fine and the other modules who need to import those classes know the dynamic names themselves alright, however this just does not seem to me the correct way of doing it, is there a method or built in method that would add class definition or a dictionary into the current module namespace?
I wrote this definition for my class:
class myClass:
def __init__(self, composed_objects: list[myClass]=[]):
self.composed_objects = composed_objects
But I'm getting this error: name 'myClass' is not defined. I thought it was possible to have a class composed as itself in python, since I'm sure I've worked with classes like that in the past, like for example linked lists. So why do I get this error and how do I fix it? Thank you!
I am a beginner to python 3 and I have a question. In pandas, is read_csv() a class or a method ?
I suspect read_csv() is a class because after you call data = pd.read_csv()
, you can subsequently call data.head(), an action only possible with a class, because of plenty of methods within this class.
For example:
from sklearn.impute import SimpleImputer
imp_mean = SimpleImputer( strategy='median')
imp_mean.fit(impute_num)
imputed_num = imp_mean.transform(impute_num)
imputed_num
As shown above, with the SimpleImputer class, first create an object, and then call the methods from that same object. It appears to be just the same as the pd.read_csv() , so I think read_csv() must be a class.
I just checked the documentation for read_csv(), which claims it returns a dataframe .But if it is a method, why can it continue to use other methods after read_csv()?
from my understanding so far, the method should only return a value and shouldn't continue to use other methods.
Is it necessary to differentiate what type it is when using a new function, method or class? Or should I just think of all of them as an object, because everything in Python is an object.
It's not a class or a method. It's a function. The resulting DataFrame is just the return value of read_csv(), not an instance of the read_csv class or something like that.
Well my understanding is pd is a class, read_csv() is a method of pd.
And the method returns an instance/object of pd (in your case data)
As data is an instance of a class, it should have all the member methods of the class pd.
I am new to python. I am using the anaconda prompt to run my code. I am trying to import a class from another module but I keep getting errors such as cannot find reference to the class.
P.S please don't negative mark this, or else I will lose the privilege of asking questions
I have already provided an __init__ function.
The module itself runs just fine.
I have used from parser import Parser
I have used from parser import * statement as well
My Parser class
class Parser(object):
def __init__(self, tokens):
self.tokens = tokens
self.token_index = 0
My main class
from parser import Parser
I expected it to normally import the class, but it is unable to.
I keep getting the cannot import name 'Parser' from 'parser' (unknown location) when I use from parser import Parser
parser is also the name of a Python module in the standard library.
It's likely there is a name conflict, and that Python is importing the module from the standard library.
I changed the module name to mparser and it works!
I want to do the semantic checking for a language and i use ANTLR4 to generate parser and visitor class. However i met a problem.
If i use this method print(type(newList[0].expression()))
I will get a type like this <class 'IDILParser.IDILParser.IdenetExpressionContext'>
However, if i run the code below, i will get a error like this NameError: name 'IDILParser' is not defined
Can i ask how to fix this problem? Thanks!
from antlr4 import *
if __name__ is not None and "." in __name__:
from .IDILParser import IDILParser
else:
from IDILParser import IDILParser
class IDILVisitor(ParseTreeVisitor):
def visitAssign(self, ctx:IDILParser.AssignContext):
if type(newList[0].expression()) is IDILParser.IDILParser.IdenetExpressionContext:
...
You did from IDILParser import IDILParser, which means the IDILParser in your code already acutally refers to IDILParser.IDILParser.
So try taking away that one layer:
if type(newList[0].expression()) is IDILParser.IdenetExpressionContext:
...
Btw, when in doubt if your code is being run as a module or as a script (aka relative imports do work or not), you could also do the following:
try:
from .IDILParser import IDILParser
except ImportError:
from IDILParser import IDILParser