I'm having problem accessing the data member in python. Not sure why.
These are my files:
# main.py
from myprocess import DataProcess as dp
myprocess = dp('apple')
myprocess.process_files()
Now for the file where i have a class
#myprocess.py
class DataProcess:
def __init__(self, file1):
self.file1=file1
#classmethod
def process_files():
print(self.file1)
In the process_files method, I have an error :
Class 'DataProcess' has no 'file1' member
Where have I gone wrong?
You can't use self parameter inside a classmethod. The idea of class method is that the method belongs to the class itself, and not to an instance of the class. Hence if you delete the #classmethod decorator, your code should work
Related
I have a class I would like to add typehints to that looks as following:
import yaml
class TestClass(dict):
#classmethod
def load(cls, fname) -> "TestClass":
return cls(yaml.safe_load(""))
#property
#abc.abstractmethod
def test(self):
raise
when I run mypy on a module containing only this class I get the following error message:
error: Cannot instantiate abstract class 'TestClass' with abstract attribute 'test'
From what I have understood from other posts this has something to do with when the 'test' method is instantiated when executing the load method. Is there a way to fix this issue using typehints alone or would I need to adjust my code here?
What mypy is telling you is that TestClass.load(...) will fail, because it will try to create an instance of the abstract class TestClass.
We can fix this by requiring that cls can be called with whatever yaml.safe_load returns (I'm assuming dict here), and returns an instance of TestClass:
from typing import Callable
import abc
import yaml
class TestClass(dict):
#classmethod
def load(cls: Callable[[dict], TestClass], fname) -> "TestClass":
return cls(yaml.safe_load(""))
#property
#abc.abstractmethod
def test(self):
raise
Note that TestClass.load("foo") will now also pass type checking. This is fair to some extent, because it's also fine at runtime, until you call test() on the created instance. I think this might be a limitation of how mypy implements protocols.
I have searched all the related this stackoverflow question but its not satisfied my issue.
BaseHandler.py
class BaseHandler(object):
def __init__(self, rHandler, path, param):
self._rHandler = rHandler
self._server = self._rHandler.server
self._path = path
self._param = param
def _getElement(self, name):
return name + "append"
MyClass.py
class MyClass(BaseHandler.BaseHandler):
def getA(self):
print "Some info"
def getB(self):
el = self._getElement("T") #baseclass method
print ebl
I wanted to call getB from the below class.
RThread.py
import MyClass
class RThread(object):
def someMethod(self):
clr = MyClass.MyClass
clr.getB()
I am getting the following error:
TypeError: unbound method getB() must be called with MyClass instance as first argument (got nothing instead)
When I try the following:
clr = MyClass.MyClass()
I am getting the following error:
init() takes exactly 4 arguments (1 given)
So kindly help me how to call this method from different class.
You need to instantiate the class in order to call a method on it.
def someMethod(self):
clr = MyClass.MyClass(*args)
clr.getB()
In the case you want the method to be callable from the class you need to use either #staticmethod or #classmethod
#staticmethod
def getB():
return self._getElement("T")
However, you are using the self. notation which requires an instance. So you would need to flag the _getElement method with #staticmethod as well. Static methods do not have access to the parent class. You can use the #classmethod decorator to do so.
#classmethod
def getB(cls):
return cls._getElement("T")
You're not calling the method correctly; you need to create an object. This is how you create an object, which is what you were doing, except you weren't passing in enough parameters.
clr = MyClass.MyClass()
Since MyClass inherits from BaseHandler and you did not override its constructor, you're using the constructor from BaseHandler, which has four arguments, one of which is self.
def __init__(self, rHandler, path, param):
...
So, try something like this:
clr = MyClass.MyClass(arg1, arg2, arg3)
clr.getB()
I want to test a method inside a class which updates the value of a member variable. However class takes constructor arguments which are not required in the method to test.
class SimpleClass(Database):
count = None
def intoTwo(self, v):
self.count = 2*v
Now I am testing method as follows
import unittest
import mock
class TestSimpleClass(unittest.TestCase):
#mock.patch('SimpleClass', autospec=True)
def test_intoTwo(self, mock_simpleclass):
mock_instance = mock_simpleclass.return_value
mock_instance.intoTwo(2)
self.assertEqual(mock_instance.count,4)
I am getting following error:
<NonCallableMagicMock name='SimpleClass().count' id='139921148836112'>
Please suggest the solution for this. I count not find something relevant in other posts or blogs.
I am confused even after checking many questions asked in SO. I have 2 different class (2 different script) & I want to inherit super class's __init__ method's parameters.
script1.py
class MainClass():
def __init__(self,params):
self.one=params['ONE']
self.two=params['TWO']
self.three=params['THREE']
self.four=params['FOUR']
self.five=params['FIVE']
def a():
#---------
#somecode
#Initializing other class's object to access it's method.
s=SubClass() #HERE I WANT TO PASS 'PARAMS' (WHICH IS A DICTIONARY)
s.method1(....)
script2.py
class SubClass(SuperClass):
def __init__(self,params):
#Here I want all the parameters inside the 'param' in super class.
#(one,two,three...., etc).
#By checking some SO questions, I changed class SubClass() -->
#class Subclass(SuperClass) & below line:
MainClass.__init__(self,params) #But technically I don't have anything
#in param in subclass.
def method1():
#some code...
Since sub class's param doesn't have anything, It gives me an error:
self.one=params['ONE']
TypeError: 'int' object has no attribute '__getitem__'
I am not getting:
How can I access all the parameters of super class to sub class in a simplest way? I don't want to pass individual arguments (like self.one, self.two..) to the sub class.
If I am calling third class inside SubClass -> method1 --> Call 3rd class same as passing 'params'. Is it possible?
Is this what you need?
script1.py
class MainClass():
def __init__(self,params):
# Save params for use by a
self.params = params
self.one=params['ONE']
self.two=params['TWO']
...
self.five=params['FIVE']
def a():
s=SubClass(self.params)
s.method1(...)
script2.py
class SubClass(SuperClass):
def __init__(self,params):
MainClass.__init__(self,params)
def method1():
#some code...
You can pass any and all the non-keyword arguments from the subclass's __init__()to the superclass's like this:
class SubClass(SuperClass):
def __init__(self, *params):
MainClass.__init__(self, *params)
...
This same idea will work for other methods, too.
I'm trying to subclass a class from another python script.
I've done the following when subclassing from within the same file, and it works.
widge.py
class widget(object):
def __init__(self,bob):
#do something
class evenWidgetier(widget):
def __init__(self, bob):
widget.__init__(self,bob)
#do something
But once I add in inheritance from another file..
superWidget.py
import widge
class superWidgety(widge.evenWidgetier):
def __init__(self, bob):
widge.widget.__init__(self,bob)
#do something
I get an error:
unbound method __init__() must be called with widget instance as first argument
Is there a way I can subclass a class from another package that works?
.
And out of curiosity, what's the deal?
Substantively this looks identical to me. I can call a class from another file by using the widge.widget(), so that method seems established. And I can subclass when the class is in the same file by referencing the class in the declaration. What is it about using a class from an import in a declaration that breaks? Why does it see itself as the right method when in the same file, but sees itself as an unbound method when imported?
The specifically, my code is this (stripping the parts that shouldn't affect this.
Attributor.py
class Tracker(object):
def __init__(self, nodeName=None, dag=None):
#Tracking stuff
class Transform(Tracker):
#Does stuff with inherited class
timeline_tab.py
import Attributor as attr
class timeline(attr.Transform):
#some vars
def __init__(self, nodeName=None):
attr.Transform.__init__(self,nodeName=nodeName)
#Additional init stuff, but doesn't happen because error on previous line
In superWidget.py change the SuperWidget to use super
import widge
class superWidgety(widge.evenWidgetier):
def __init__(self, bob):
super(SuperWidget,self).__init__(bob)
#do something