This question already has answers here:
What is the purpose of the `self` parameter? Why is it needed?
(26 answers)
Closed 4 months ago.
In the example below, classes AA and BB are instantiated with params a and b and feature the foo method. The only difference between classes AA and BB is that in the AA foo method, the intermediate variable z is prefixed with the class instance reference self while in class BB it is not. What is the correct methodology here? When should self be used within class methods and when should it not be used? I've always been confused by this!
class AA:
def __init__(self, a, b):
self.a = a
self.b = b
def foo(self):
self.z = self.a + self.b
return self.z * self.a
class BB:
def __init__(self, a, b):
self.a = a
self.b = b
def foo(self):
z = self.a + self.b
return z * self.a
Neither one is "correct" per se. It depends what you want to do: If you want to keep the value around, then you could assign it to the instance. If not, then don't.
Although, if you do assign it as a public instance attribute, you'll probably want to set an initial value in __init__(), like None.
the use of the self will appear when you initiate an object from the class, so in order that the object will have an access to the variable you need to use the self
class AA:
def __init__(self, a, b):
self.a = a
self.b = b
def foo(self):
self.z = self.a + self.b
return self.z * self.a
class BB:
def __init__(self, a, b):
self.a = a
self.b = b
def foo(self):
z = self.a + self.b
return z * self.a
A = AA(1, 2)
A.foo()
print(A.z) # will print the value
B = BB(1, 2)
B.foo()
print(B.z) # will not print the value, "z" attribute is not defined
Related
Imagine I have:
class ABC():
def main(self, x):
self.x = x
class A(ABC):
def afunction(self):
self.a = 2
class B(ABC):
def bfunction(self):
self.b = self.a * self.x
return self.b
How is it possible that class B inherits the self.a and self.x from class A and ABC? (I do not care about inheriting the methods)
If I understand correctly, what you want is to get B to inherit from A.
Notice that what will happen is that it will inherit A variables, and because A inherits from ABC, B will inherit ABC's variables as well.
Also, please note that you will have to initialize the x variable for example inside an B object in order to use the bFunction, and in general it is proper coding to set a constructor as follows:
class ABC():
def __init__(self, x=0):
self.x = x
def main(self, x):
self.x = x
class A(ABC):
def __init__(self, a=2):
super().__init__()
self.a = a
def afunction(self):
self.a = 2
class B(A):
def __init__(self, b=0):
super().__init__()
self.b = b
def bfunction(self):
self.b = self.a * self.x
return self.b
b = B()
b.main(3)
b.afunction()
print(b.bfunction())
Output:
6
If B inherits from A, which inherits from ABC, then B will have ABC and A's methods but neither the 'x' or 'a' attributes which are only set after the methods are run. This works if you rewrite B as:
class B(A):
def bfunction(self, x):
self.main(x)
self.afunction()
self.b = self.a * self.x
return self.b
b = B()
print(b.bfunction(10))
You have to supply 'x' to b.bfunction so that self.b = self.a * self.x works.
Getting below Attribute error while running below code. Class member function is accessed using self still it is giving error.
class A:
def __init__(self):
self.a=1
def f1(self):
self.b=2
def f2(self):
self.c=3
print(self.a,self.b,self.c)
self.f2()
model = A()
model.f1()
Error:
AttributeError: 'A' object has no attribute 'f2'
A does not have an attribute f2, but it does have an attribute f1 that calls a function f2. f2 is not an instance attribute.
In this case c is no longer an instance attribute, or data attribute, it is now just a local variable. This may or may not be what you were
going for.
class D:
def __init__(self):
self.a = 1
def f1(self):
# Instance attribute declared outside of __init__
self.b = 2
def f2():
c = 3
print(self.a, self.b, c)
f2()
Depending on your development environment you may or may not get a warning about instance attributes being declare outside of the __init__ function. It isn't necessary that you declare them this way, however, it improves readability.
class B:
def __init__(self):
self.a = 1
self.b = 2
self.c = 3
def f1(self):
def f2():
print(self.a, self.b, self.c)
f2()
This next block is slightly more explicit in what it says about the intent of the code.
class A:
def __init__(self):
self.a = 1
self.b = 2
self.c = 3
def f1(self):
def f2():
return '{} {} {}'.format(self.a, self.b, self.c)
return f2()
Perhaps you want f2() to be called using method attributes of the
self argument in which case:
class A2:
def __init__(self):
self.a = 1
self.b = 2
self.c = 3
def f2(self):
print(self.a, self.b, self.c)
def f1(self):
"""Do something that requires calling the self.f2()
print function.
"""
self.f2()
You do not need self when calling the nested function and nor does it need to be contained in the function signature:
class A:
def __init__(self):
self.a=1
def f1(self):
self.b=2
def f2():
c=3
print(self.a,self.b, c)
f2()
model = A()
model.f1()
Output:
1, 2, 3
Its not clear to me that you actually need to define a function within a method just to call it.
So, your code could just as easily be this:
class A:
def __init__(self):
self.a = 1
def f1(self):
self.b = 2
self.f2()
def f2(self):
self.c = 3
print(self.a, self.b, self.c)
model = A()
model.f1()
Output:
1 2 3
class A(object):
def __init__(self):
self.a = 1
class B(A):
def __init__(self):
A.__init__(self)
self.a = 2
self.b = 3
class C(object):
def __init__(self):
self.a = 4
self.c = 5
class D(C, B):
def __init__(self):
C.__init__(self)
B.__init__(self)
self.d = 6
obj = D()
print(obj.a)
My understanding is that python will first search class C then B then A to get a. So print(obj.a) will print out 4 when searching class C. But the answer is 2. This means that Python got self.a = 2 from class B instead of self.a = 4 from class C. Can anyone explain the reasons? Thank you
There is no search going on here. You are making explicit, direct calls to unbound methods, passing in self manually. These are simple function calls, nothing more.
So this is just a question of tracing the execution order:
D() -> D.__init__(self)
C.__init__(self)
self.a = 4
B.__init__(self)
A.__init__(self)
self.a = 1
self.a = 2
So a is assigned 4, then 1, then 2.
I am starting to work with classes in Python, and am learning how to create functions within classes. Does anyone have any tips on this sample class & function that I am testing out?
class test:
def __init__(self):
self.a = None
self.b = None
self.c = None
def prod(self):
return self.a * self.b
trial = test
trial.a = 4
trial.b = 5
print trial.prod
Ideally the result would be to see the number 20.
You need to:
Create an instance of test.
Invoke the prod method of that instance.
Both of these can be accomplished by adding () after their names:
trial = test()
trial.a = 4
trial.b = 5
print trial.prod()
Below is a demonstration:
>>> class test:
... def __init__(self):
... self.a = None
... self.b = None
... self.c = None
... def prod(self):
... return self.a * self.b
...
>>> trial = test()
>>> trial.a = 4
>>> trial.b = 5
>>> print trial.prod()
20
>>>
Without the parenthesis, this line:
trial = test
is simply assigning the variable trial to class test itself, not an instance of it. Moreover, this line:
print trial.prod
is just printing the string representation of test.prod, not the value returned by invoking it.
Here is a reference on Python classes and OOP.
Ideally you could also pass in the values to a, b, c as parameters to your object's constructor:
class test:
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def prod(self):
return self.a * self.b
Then, constructing and calling the function would look like this:
trial = test(4, 5, None)
print trial.prod()
Assume that we have an object k of type class A. We defined a second class B(A). What is the best practice to "convert" object k to class B and preserve all data in k?
This does the "class conversion" but it is subject to collateral damage. Creating another object and replacing its __dict__ as BrainCore posted would be safer - but this code does what you asked, with no new object being created.
class A(object):
pass
class B(A):
def __add__(self, other):
return self.value + other
a = A()
a.value = 5
a.__class__ = B
print a + 10
a = A() # parent class
b = B() # subclass
b.value = 3 # random setting of values
a.__dict__ = b.__dict__ # give object a b's values
# now proceed to use object a
Would this satisfy your use case? Note: Only the instance variables of b will be accessible from object a, not class B's class variables. Also, modifying variables in a will modify the variable in b, unless you do a deepcopy:
import copy
a.__dict__ = copy.deepcopy(b.__dict__)
class A:
def __init__(self, a, b):
self.a = a
self.b = b
class B(A):
def __init__(self, parent_instance, c):
# initiate the parent class with all the arguments coming from
# parent class __dict__
super().__init__(*tuple(parent_instance.__dict__.values()))
self.c = c
a_instance = A(1, 2)
b_instance = B(a_instance, 7)
print(b_instance.a + b_instance.b + b_instance.c)
>> 10
Or you could have a sperate function for this:
def class_converter(convert_to, parent_instance):
return convert_to(*tuple(parent_instance.__dict__.values()))
class B(A):
def __init__(self, *args):
super().__init__(*args)
self.c = 5
But using the 2nd method, I wasn't able to figure out how to pass additional values