class myclass():
def fun(self):
a = 12
return a
b = fun()
TypeError: fun() missing 1 required positional argument: 'self'
The idea is to be able to use b inside another def, like
class myclass():
def fun(self):
a = 1
return a
b = fun()
def fun2(self):
c = self.b + 2
Is this possible?
Since myclass.fun is an instance method, if you want to cache its result you should do that in an instance attribute (defined in __init__) rather than a class attribute.
class myclass():
def __init__(self):
self.b = self.fun()
def fun(self):
a = 1
return a
def fun2(self):
c = self.b + 2
Related
I'm not even sure if this is possible. What I'm trying to do is having an object call a method, which would reassign a new class object to the variable
Definition:
class A():
def __init__(self):
self.number = 1
def becomeB(self):
# a method that will assign this variable a class B object
class B():
def __init__(self):
self.name = "I am B"
What I'm trying to achieve:
myObj = A()
myObj.becomeB()
print(myObj.name)
Output: I am B
It doesn't make any sense to convert object of type A to be of type B.
Instead, I would recommend you to make becomeB a function that returns object B.
For example:
class B():
def __init__(self):
self.name = "I am B"
class A():
def __init__(self):
self.number = 1
def becomeB(self):
return B()
myObj = A()
b = myObj.becomeB()
print(b.name) # output: I am B
If you want an object to behave like an instance from another class you can reassign the __class__ attribute:
def becomeB(self):
self.__class__ = B
Here's a more complete example:
class A:
def __init__(self, name):
self.name = name
def foo(self):
return f'A says: Hello {self.name}'
def becomeB(self):
self.__class__ = B
class B:
def foo(self):
return f'B says: Hello {self.name}'
a = A('World')
print(a.foo()) # prints: A says: Hello World
a.becomeB()
print(a.foo()) # prints: B says: Hello World
I want local variable of a class to be changed by other class. My script is similar to the following :
import datetime
b = []
class P:
def __init__(self):
self.count = 1
self.create()
def create(self):
global b
a = C(self.count)
for i in range(10):
a.print_name()
print b
class C:
def __init__(self, *data):
self.test = data[0]
#staticmethod
def print_name():
global b
b.append(datetime.datetime.now())
o = P()
How to avoid use of a global variable . On web i found use of "super " can resolve the issue . Please help in this regard .
Make C constructor to accept P instance. And call the method of P to append item to instance attribute of P object.
class P:
def __init__(self):
self.count = 1
self.items = []
self.create()
def append(self, item):
self.items.append(item)
def create(self):
a = C(self, self.count) # <-- Pass P instance (self)
for i in range(10):
a.print_name()
print self.items
class C:
def __init__(self, p_instance, *data):
self.p_instance = p_instance # <-- Save P instance to use later
self.test = data[0]
def print_name(self):
self.p_instance.append(datetime.datetime.now()) # <-- Call p instance method
You are probably looking for a class attribute. If you add b as an attribute to the C class, it can be accessed as C.b and C().b, i.e. from a reference to the class or any instance.
class C(object): # classes in py2 should inherit from object!
b = [] # b inside C definition
#classmethod
def print_name(cls):
cls.b.append(datetime.datetime.now())
class P(object):
def __init__(self):
self.count = 1
self.create()
def create(self):
a = C(self.count)
for i in range(10):
a.print_name()
print C.b # or a.b
Of course, you can also place b on P. In this case, do
def print_name():
P.b.append(datetime.datetime.now())
class A:
def __init__(self):
self.i = 0
def demo(self):
self.a=1
class B(A):
def __init__(self, j = 0):
super().__init__()
self.j = j
print(self.i)
self.demo()
def demo(self):
print(self.a)
def main():
b = B()
print(b.i)
print(b.j)
main()
why am i not able to access self.a inside class b
does prefixing a variable with self. will make it an instance variable
Thanks
When you include a demo method for both classes, the most recently-defined one masks the others. Since you define B after you define A but before you call any of the methods in A, demo will try to access a variable that was never defined. You should either call demo within A (in __init__, probably), or change the name of demo in B to something unique, which will allow you to access both methods (probably the best approach, since they do different things and you want to make use of both).
Because you overwrite demo method on B class.
If you want to access self.a add it to __init__ method of A class or call parent demo method like this:
def demo(self):
super().demo()
print(self.a)
It is because instance variable b is not initiated within __init__ of A
Because class A.demo() is not executed:
class A:
def init(self):
self.i = 0
def demo(self):
self.a=1
class B(A):
def __init__(self, j = 0):
super().__init__()
self.j = j
print(self.i)
super().demo()
self.demo()
def demo(self):
print(self.a)
def main():
b = B()
print(b.i)
print(b.j)
main()
Have written a simple code like this:
class Operations:
#global a,b
a=1
b=2
def __init__(self):
print(self,"object has been created")
def add(self):
#a = 2
#b = 3
return a+b
obj1=Operations()
sum=obj1.add()
print(sum).
when i run this code, am getting this error NameError: name 'a' is not defined.
can you please explain why variables a and b are not accessible in the method 'add' which is defined in the same class?
Note:when am declaring variables as a global, am able to access the variables inside the 'add' method.
You need to use the self keyword.
What does self do?
a = 1
class Operations:
a = 2
def fun1(self):
return a
def fun2(self):
return self.a
obj = Operations()
print(obj.fun1())
print(obj.fun2())
Output:
1
2
Solution for you case:
class Operations:
a=1
b=2
def __init__(self):
print(self,"object has been created")
def add(self):
return self.a + self.b
obj1=Operations()
print(obj1.add())
Output:
<__main__.Operations object at 0x100663588> object has been created
3
Use the class reference
Value= self.a + self.b
Is this the answer that you need? if you're writing a class, use self.value instead global value:
class Operations:
def __init__(self):
self.a = 1
self.b = 2
print(self, "object has been created")
def add(self):
return self.a + self.b
obj1 = Operations()
print(obj1.add())
How can I set a class variable from inside a function inside another function?
var.py
class A:
def __init__(self):
self.a = 1
self.b = 2
self.c = 3
def seta(self):
def afunction():
self.a = 4
afunction()
def geta(self):
return self.a
run.py
cA = A()
print cA.a
cA.seta()
print cA.a
print cA.geta()
python run.py
1
1
1
why does a not equal 4 and how can I make it equal 4?
Edit:
Thanks everyone - sorry, I just saw now. I accidentally was off by a _ in one of my names.... so my scope is actually all ok.
The problem is that there are multiple self variables. The argument passed into your inner function overwrites the scope of the outer.
You can overcome this by removing the self parameter from the inner function, and making sure you call that function in some way.
class A:
def __init__(self):
self.a = 1
self.b = 2
self.c = 3
def seta(self):
def afunction(): # no self here
self.a = 4
afunction() # have to call the function
def geta(self):
return self.a
As others have mentioned, afunction is never called. You could do something like this:
class A:
def __init__(self):
self.a = 1
def seta(self):
def afunction(self):
self.a = 4
afunction(self)
def geta(self):
return self.a
a = A()
print a.a
a.seta()
print a.a
Here we actually call afunction and explicitly pass it self, but this is a rather silly way to set the attribute a -- especially when we can do it explicitly without the need for getters or setters: a.a = 4
Or you could return the function:
def seta(self):
def afunction(): #Don't need to pass `self`. It gets picked up from the closure
self.a = 4
return afunction
and then in the code:
a = A()
a.seta()() #the first call returns the `afunction`, the second actually calls it.
Inside seta, you define a function
def afunction(self):
self.a = 4
...that would set self.a to 4 if it would ever be called. But it's not called anywhere, so a is unchanged.
As several others have said, you need to actually call functiona at some point. Comments won't let me type this intelligably so here's an answer:
def seta(self):
def functiona(self): #defined
self.a = 4
functiona() #called
How can you make it equate to 4:
class A:
def __init__(self):
self.a = 1
self.b = 2
self.c = 3
def seta(self):
##def afunction(self): (remove this)
self.a = 4
def geta(self):
return self.a
Tricky part: Why does is not equate to 4...
Currently a is set to 4 only via "afunction". Since afunction is never called it never executes.. The seta has "afunction" nested inside but not called... similar to member variables within a classs.